5

A common annoyance with using Swift is that subclasses must implement init?(coder) even if you don't use Storyboard.

required init?(coder aDecoder: NSCoder) {
  fatalError("init(coder:) has not been implemented")
}

It's not elegant. How can I avoid overwriting it in a subclass?

2 Answers 2

7

If you have a base class, override it in the base class and add the @available(*, unavailable) flag so that its subclasses can avoid overriding the method, and this method also removed from code completion.

@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
  fatalError("init(coder:) has not been implemented")
}
Sign up to request clarification or add additional context in comments.

Comments

0

Also if you don't have a parent class and if you have to implement init?(coder:) you can implement a global function as below to avoid string coding in every new class:

@inlinable
@inline(__always)
public func fatalErrorNotImplemented(
    function: String = #function,
    file: StaticString = #file,
    line: UInt = #line
) -> Never {
    fatalError(
        function + " not implemented",
        file: file,
        line: line
    )
}

Usage:

final class AnotherView: UIView {
    let value: Any

    init(config: Any) {
        self.value = value
        super.init(frame: .zero)
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalErrorNotImplemented() // No strings
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.