Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - How to forbid an initializer?

Consider the following controller class with a delegate:

@objc protocol FooControllerDelegate {
}

@objc class FooController: UIViewController {
    var delegate: FooControllerDelegate

    init(delegate: FooControllerDelegate) {
        self.delegate = delegate
        super.init(nibName: nil, bundle: nil)
    }

    // TODO: How do we forbid this init?
    required init(coder aDecoder: NSCoder) {
        // TODO: Fails to compile.
        super.init(coder: aDecoder) 
    }
}

Is there any way to forbid the usage of the -initWithCoder: equivalent, without making the delegate implicitly unwrapped, and placing an assert(false) inside the method?

Ideally, it won't be necessary to write the init(coder:) with each subclass at all, and have it implicitly forbidden.

like image 634
Sea Coast of Tibet Avatar asked Feb 21 '15 10:02

Sea Coast of Tibet


1 Answers

  • If the goal to forbid usage of all designated initializers besides yours then there's no language feature at this moment. This applies to all kinds of methods.

Overriding method must be accessible as it's enclosing type

  • If the goal is to avoid empty override of init(coder:) each time you adding custom initialiser then think about convenience keyword. Swift's safety paradigm assumes that class either adds 'additional' init or has to modify behaviour of all required initialisers.

"Automatic Initializer Inheritance"

like image 92
sunnycows Avatar answered Sep 30 '22 02:09

sunnycows