Getting wrong "Ambiguous reference" in init

Hi


I want to add an init function to a UIViewController to ensure that a property that I require is always going to be set. The code is this:

class XBSelectRecord: UIViewController {
        
    convenience init(labelXXX: String?)
    {
        self.init(nibName: "XBSelectRecord", bundle: nil)    ! Ambiguous reference to member 'init(labelXXX:)'
        self.heading = labelXXX
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

Clearly that should not be ambiguous. Can anyone explain what I am doing wrong here?
TIA
Mark

Accepted Answer

The error message is not just misleading, but is completely broken, IMO. You should better send a bug report.


What is bad for you is that, in Swift, when you override one designated initializer (`init(coder:)` in your case),

all other designated initializers (`init(nibName:bundle:)` in your case) are not inherited.

Class Inheritance and Initialization


So your `XBSelectRecord` does not have an initializer named `init(nibName:bundle:)`, which is causing the error.

You may need to implement the initializer explicitly:

class XBSelectRecord: UIViewController {
    var heading: String?
    
    convenience init(labelXXX: String?) {
        self.init(nibName: "XBSelectRecord", bundle: nil)
        self.heading = labelXXX
    }

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


Or else, remove both overrides:

class XBSelectRecord: UIViewController {
    var heading: String?
    
    convenience init(labelXXX: String?) {
        self.init(nibName: "XBSelectRecord", bundle: nil)
        self.heading = labelXXX
    }
}

Thanks!
I have settled on this code, and it works, and looks obvious:

class XBSelectRecord: UIViewController {
        
    
    convenience init(heading: String?)
    {
        self.init(nibName: "XBSelectRecord", bundle: nil)
        self.heading = heading
    }


I find the rules around initializers a bit confusing, so the simplicity is beguiling here.

Getting wrong "Ambiguous reference" in init
 
 
Q