Swift - Custom Type Overloading Initializers

Introduction

You can add more than one initializer to the inherited Rectangle class:

class Shape {
    //stored properties
    var length:Double = 0
    var width:Double = 0

     //improvision to make the class abstract
    private init() {
         length = 0
         width = 0
    }

    func perimeter() -> Double {
        return 2 * (length + width)
    }
}
class Rectangle: Shape {
    //override the init() initializer
    override init() {
        super.init()
    }

     //overload the init() initializer
     init(length:Double, width:Double) {
         super.init()
         self.length = length
         self.width = width
     }
}

In this case, you are overloading the initializer with two parameters: length and width .

You can now create an instance of the Rectangle class like this:

var rectangle = Rectangle (length: 5,width: 6 )

Swift adopts the following rules for initializers:

  • If a subclass does not have any initializers, then all the base class' initializers are available to the subclass.
  • If a subclass has at least one initializer, then it will hide all the initializers in the base class.

Here is an example to illustrate the preceding rules.

The following Square class inherits from the Rectangle class (which has two overloaded initializers):


class  Square :  Rectangle  {

}

When creating an instance of the Square class, you would see two initializers.

However, suppose the Square class has its own initializer, as shown here:


class Square: Rectangle {
     //initializer
     init(length:Double) {
         super.init()
         self.length = length
         self.width = self.length
     }
}

You will now be able to call only this initializer.

All the initializers in the base class (Rectangle ) will be hidden.

Related Topic