Swift - Custom Type Designated Initializers

Introduction

To pass in the values to initialize at the time of instantiation, create another initializer with parameters, as shown in the following example:


class Person {
    var firstName:String
    var lastName:String
    var email:String
    var group:Int

    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
    }
}

Here, the initializer is a designated initializer, as it initializes all the properties in the class.

You can call the designated initializer as follows:

var c2 = Person (
    firstName:"Jason",
    lastName:"Json",
    email:"a@2.net", group:0 )

You have to label the various arguments passed into it, unless you write an underscore in front of the parameter name:

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

In this case, you can call the initializer without specifying the labels:

var c2 = Person("a", "b", "a@a.net",0 )

A class is not limited to one designated initializer:

class Person {
    var firstName:String
    var lastName:String
    var email:String
    var group :Int

    //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)
     }
}

The preceding initializers are designated initializers, as they initialize all the properties in the class.

Related Topic