meaning-matters meaning-matters - 3 months ago 32
iOS Question

"Ambiguous reference to member 'init(...)" calling baseclass initializer

I have a baseclass:

class ViewController: UIViewController
{
init(nibName nibNameOrNil: String?)
{
super.init(nibName: nibNameOrNil, bundle: nil)
}

required init?(coder aDecoder: NSCoder) { }
}


a subclass:

class OneViewController: ViewController
{
private var one: One
init(one: One)
{
self.one = one

super.init(nibName: "OneNib")
}

required init?(coder aDecoder: NSCoder) { }
}


and a subclass of the above subclass:

class TwoViewController: OneViewController
{
private var two: Two
init(two: Two)
{
self.two = two

super.init(nibName: "TwoNib") <== ERROR
}

required init?(coder aDecoder: NSCoder) { }
}


At the indicated line I get the error:

Ambiguous reference to member 'init(one:)'


I don't understand why the compiler can't figure out I'm referring to
ViewController
's
init()
, like it managed to do in
One
's
init()
.

What am I missing and/or doing wrong?

Answer

I don't understand why the compiler can't figure out I'm referring to ViewController's init(), like it managed to do in One's init()

It is because, from inside TwoViewController, the compiler can't see ViewController's init. The rule is:

As soon as you implement a designated initializer, you block inheritance of initializers.

Therefore, OneViewController has only one initializer, namely init(one:). Therefore, that is the only super initializer that TwoViewController can call.

If you want ViewController's init(nibName:) to be present in OneViewController, you must implement it in OneViewController (even if all it does is to call super).

Comments