Pages

Convenience && Designated && Required Initializers

Designated Initializers:--> There are two types of Initializers in Swift. First type is Designated Initializers and Second type is Convenience Initializers. All a designated initializer do is just to initialize an object completely by sending an initializer message to its super class. The class that implements designated initializer must also implements designated initializer of its super class. Here is an example of designated initializer:

init(frame: CGRect) {
               super.init(frame: frame)
               var label = UILabel(frame: CGRect(x: 20, y: 30, width: 50, height: 30))
               label.backgroundColor = UIcolor.greenColor()
               label.title = "first Label"
}

Here in this code all you are doing is just to initialize a label using a designated initializer. When you compile your project this initializer will be the first one to call then it inturn call the designated initializer of its super class && at last it will guarantee to return you object to initialize.

Convenience Initializers:--> It is the second type of initializer && it makes it easy to create objects by providing a simple interface but it will intern call the designated initializer of of the same class to initialize an object, well thats what "convenience" means, after all. It will initialize the object conveniently, thats all. Convenient initializer are marked with "convenience" keyword. Here is an example:

convenience override init() {      //Calling the designated initializer of same class
      self.init(nibName: "NavigationViewController", bundle: nil)
        ////initializing the view Controller form specified NIB file
    }

Here in the above written code a convenience initializer is calling the designated initializer of the same class && ordering it to initialize the Navigation View Controller from a nib file.


Required Initializers:--> There is one other type of initializer named as "required" initializer in Swift. It must be overridden && re-implemented by a subclass. Usually encountered initializer of this type is init(coder: NSCoder),it is the designated initializer of the NSCoding protocol. Basically it is used so that your defined object will be created from array of bytes that are serialized. Here is an example for demonstration:

required init(coder aDecoder: NSCoder) {        
     super.init(coder: aDecoder)
}