Search code examples
swiftuiviewcontrollerinitializer

What initializer called in convenience init of UIViewController?


I often use convenience init in UIViewController to make custom initializer.

But I don't know what existing initializer of UIViewController being called when self.init().

Is it public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?)?

What is called when self.init() in convenience init of UIViewController?

final class SampleViewController: UIViewController {
    private var component: Component?

    convenience init(component: Component) {  // Custom initializer
       self.init()  // What is this initializer?
       self.component = component
    }

    override func viewDidLoad() {
       ...
    }
    ...
}

Solution

  • UIViewController.init calls UIViewController.init(nibName: nil, bundle: nil). That means that the nibName will be equal to the name of the class and bundle will be the main bundle.

    UIViewController.init is just a convenience initializer. In swift this could be implemented using default parameters UIViewController.init(nibName: String? = nil, bundle: NSBundle? = nil) but this is an old Objective-C API and Objective-C does not have default parameters and that's why there is a separate convenience init().