Wednesday, July 13, 2016

Convenience Initialisation Vs Designated Initialization


Designated initializers fully initialize an instance of a class, meaning that every property of the instance has an initial value after initialization. Looking at the Task class, for example, we see that the nameproperty is set with the value of the name parameter of the init(name:) initializer. The result after initialization is a fully initialized Task instance.
Convenience initializers, however, rely on a designated initializer to create a fully initialized instance of the class. That's why the init initializer of the Task class invokes the init(name:) initializer in its implementation. This is referred to as initializer delegation. The init initializer delegates initialization to a designated initializer to create a fully initialized instance of the Task class.
Convenience initializers are optional. Not every class has a convenience initializer. Designated initializers are required and a class needs to have at least one designated initializer to create a fully initialized instance of itself.
Ref: http://code.tutsplus.com/tutorials/swift-from-scratch-initialization-and-initializer-delegation--cms-23538
import Foundation
 
class Task: NSObject {
    var name: String
     
   convenience override init() {
        self.init(name: "New Task")
    }
     
    init(name: String) {
        self.name = name
    }
}

No comments:

Post a Comment