Swift - Convenience Initializers and Initializer Chaining

Introduction

The third type of initializer is known as a convenience initializer.

To understand its use, consider the following example:

Demo

class Person {
   var firstName:String
   var lastName:String
   var email:String
   var group:Int// w w  w .  ja  va 2  s .c  om

   //designated initializer
   init() {
      firstName = ""
      lastName = ""
      email = ""
      group = 0
   }

   //designated initializer
   init(firstName: String, lastName:String, email:String, group: Int) {
      self.firstName = firstName
      self.lastName = lastName
      self.email = email
      self.group = group
   }

   //designated initializer
   init(firstName: String, lastName:String, email:String, group: Int, timeCreated:NSDate) {
        self.firstName = firstName
        self.lastName = lastName
        self.email = email
        self.group = group
        print(timeCreated)
   }

   //convenience initializer; delegate to the designated one convenience 
   init(firstName: String, lastName:String, email:String) {
         self.init (firstName: firstName, lastName: lastName, email: email, group: 0)
   }

   //convenience initializer; delegate to another convenience initializer-convenience 
   init(firstName: String, lastName:String) {
         self.init (firstName:firstName, lastName:lastName, email:"")
   }

   //convenience initializer; delegate to another convenience
   // initializer convenience 
   init(firstName: String) {
         self.init (firstName:firstName, lastName:"")
   }

}

The convenience initializer with the fewest parameters calls the one with the next fewest number of parameters, and so on.

This is call initializer chaining.

Finally, the last convenience initializer calls the designated initializer.

Initializer chaining enables you to ensure that all properties in a class are fully initialized before use.

Related Topic