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.
You need to override the
init(nibName:bundle:)
initializer, and provide theinit(coder:)
required initializer, and initializetap
in both of them:Also, be sure when calling the superclass initializer that you don't just pass
nil
for thenibName
andbundle
. You should pass up whatever was passed in.I came across this Question of You asked long way Back. But no one has provided a basic answer to the question. It's a basic in Swift that:- Subclass must initialize its variables before it's super class initialization is complete.
Hence as Ankit Goel mentioned the crash :- "Must call a designated initializer of superclass"
Hence updated code would be:-
I think you have to add
or
You have to write init too. Don't remove it
Hope it helps
I used:
Some people suggested:
But this gives you an infinite loop.
You can just create a convenience initializer instead, convenience initializers don't override the init() instead it just calls it making things easier.
All of these answers are half-answers. Some people are experiencing infinite loops in related posts because they are only adding the
convenience init()
(it recursively calls itself if you don't providing a distinctinit()
method for it to invoke), while other people are neglecting to extend the superclass. This format combines all the solutions to satisfy the problem completely.Edit: Also, if you want to initialise any class properties using parameters passed into your
convenience init()
method without all the overriddeninit()
methods complaining, then you may set all those properties as implicitly unwrapped optionals, which is a pattern used by Apple themselves.