Home > Enterprise >  Initializer chaining ('super.init') cannot be nested in another expression
Initializer chaining ('super.init') cannot be nested in another expression

Time:09-09

Why do I receive the below error in this code?

final class HomeViewController : someBaseClass {    

init(something: SomethingProtocol) {
            someFunction {
                self.something = something
                super.init(nibName: Self.nibName(), bundle: Bundle.main) //here
            }
        }
}

Initializer chaining ('super.init') cannot be nested in another expression

CodePudding user response:

That's because of the two phase initialization principle used by swift:

  • first the (designated) initialiser must make sure that every stored property of the class is initialized
  • then only it can call the superclass initialiser but still without referring to self in the parameters,
  • then it can make whatever it wants, and in particular call instance methods, read the values of instance properties, or refer to self (because at least all the properties of the class hierarchy would be initialized).

In your code, you're first calling a function using a trailing closure that is supposed to do the necessary steps. This is not allowed, since the function does not know the state of the initialization and could assume that the object already finished phase 1. This is why you get this error message.

Moreover the call to super.init() refers to self in the parameters, whereas phase 1 of the initialization is not yet finished and it would still be unsafe to refer to self. So even if you would do things properly before calling the closure, you'd get an error message:

init(something: SomethingProtocol) {
    self.something = something
    super.init(nibName: self.nibName(), bundle: Bundle.main) // OUCH!!
    someFunction {
            ...
    }
}

The error message would be explicit as well: "'self' used in method call 'nibName' before 'super.init' call". This is because the parameters must be evaluated before the call can be made and breaks again the two phase initialization.

  • Related