How to write init methods of a UIViewController in Swift

Ankit Goel picture Ankit Goel · Jun 6, 2015 · Viewed 87.6k times · Source

I am unable to add init method to the following UIViewController class. I need to write some code in the init method. Do i have to write init(coder) method? Even when I add the coder and decoder methods I still get errors. I also tried using the init method without any parameters but that also does not seem to work.

class ViewController: UIViewController {

    var tap: UITapGestureRecognizer?

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?)   {
        super.init(nibName: nil, bundle: nil)
        tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
    }

...
...
}

If I call the super.init() method without parameters the error is "Must call a designated initializer of super class" and if I pass the parameter nib and bundle then error is "Required initializer init(coder)".

Even when I add init(coder) and init(decoder) it does not work.

Answer

Glauco Neves picture Glauco Neves · Sep 2, 2015

I used:

convenience init() {
    self.init(nibName:nil, bundle:nil)
}

Some people suggested:

convenience init(){
    self.init()
}

But this gives you an infinite loop.