Vincent Sit
Vincent Sit

Reputation: 2352

Swift how to avoid override init?(coder) in subclass

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?

Upvotes: 5

Views: 902

Answers (2)

eli7ah
eli7ah

Reputation: 355

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
    }
}

Upvotes: 0

Vincent Sit
Vincent Sit

Reputation: 2352

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")
}

Upvotes: 7

Related Questions