Swift - Calling Initializers in Subclasses

Introduction

When a subclass inherits a base class and has its own initializer, you need to call the initializer in the base class.

Consider the following example:

class Employee: Person {
     init(firstName:String, lastName:String, email:String) {

     }
}

Employee inherits from the Person base class and it overrides the initializers in Person.

In this case, you need to call the base class's initializer before you can do anything with the base class's properties.

Trying to access any of the base class's properties will result in an error:


class Employee: Person {

    init(firstName:String, lastName:String, email:String) {
         //error
         self.firstName = firstName
    }
}

However, you have to follow one rule: The subclass can only call the base class's designated initializer.

The following will fail, as you are calling the base class's convenience initializer, not the designated initializer:

class Employee: Person {
    init(firstName:String, lastName:String, email:String) {
         //error; can only call designated initializer(s)
         super.init (firstName: firstName, lastName: lastName, email: email)
    }
}

You need to call one of the base class's designated initializers:

class Employee: Person {
     init(firstName:String, lastName:String, email:String) {
          super.init (firstName: firstName, lastName: lastName, email: email, group: 9)
     }
}

You can now create an instance of Employee as follows:

var e1 = Employee ( firstName: "John", lastName: "Doe",email: "a@example.com")
                           

Related Topic