user10497264
user10497264

Reputation:

Swift: 'super.init' isn't called on all paths before returning from initializer?

I am getting this error on the last brace of a init in a class of mine. The class looks something like the following (I market the spot where error happens):

class RecordingViewController: UIViewController, AVCaptureFileOutputRecordingDelegate {

    let cameraButton:UIButton?
    let camPreview:UIView?

    init (cameraButton: UIButton!, camPreview: UIView!) {
        self.cameraButton = cameraButton
        self.camPreview = camPreview

    } //get error here

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

    //do a bunch of other stuff
}

I have looked here and here for a solution but both seem like solutions that are either really bad or that are too specific to that question, thus they have not work for me.

I was hoping for a solution to my problem done in such a way that it can help me understand why this error is happening.

Upvotes: 18

Views: 38185

Answers (2)

Diya Li
Diya Li

Reputation: 1088

Here is what I found on Swift Programming Language:

In the first phase, each stored property is assigned an initial value by the class that introduced it. Once the initial state for every stored property has been determined, the second phase begins, and each class is given the opportunity to customize its stored properties further before the new instance is considered ready for use.

A designated initializer must ensure that all of the properties introduced by its class are initialized before it delegates up to a superclass initializer.

Hope this can explain that question.

Upvotes: 2

Tal Cohen
Tal Cohen

Reputation: 1457

Since you inherit from UIViewController, you should call super.init right after you set the variables in your init function

When you inherit a class and implement a new init function or override its own init function you should (almost) always call super.init. Let's take your example, you inherited from UIViewController. UIViewController has a few init functions that you can use to initialize a view controller. if you don't call super.init, all the code inside those functions will not get called and possibly the view controller won't get initialized.

Anyway, this piece of code should work for you:

class ViewController: UIViewController {

    var button: UIButton?

    init(button: UIButton) {
        self.button = button
        super.init(nibName: nil, bundle: nil)
    }

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

}

Upvotes: 40

Related Questions