Swift : Initializer delegation — Part 2

In previous post I had discussed about initializer delegation in value types. In this post, I will talk about designated and convenience initializers and initializer delegation in classes.

Designated initializers

Designated initializers are the primary initializers of a class. A designated initializer fully initializes the properties of a class and calls an appropriate superclass initializer to continue the initialization process up the chain. Every class must have at least one designated initializer. This requirement is sometimes satisfied by automatic initializer inheritance which I will discuss later.

Convenience initializers

Convenience initializers are secondary, supporting initializers for a class. You can have a convenience initializer which calls a designated initializer with some of the parameters as default values. A class may or may not have convenience initializers.

class Food{
    var name : String
    //designated initializer
init(name : String){
self.name = name
    //calls designated initializer with default name parameter
convenience init(){
self.init(name : “Unnamed”)

Rules for initializer delegation

  1. A designated initializer must call a designated initializer from it’s immediate super class.
  2. A convenience initializer must call a initializer from the same class.
  3. A convenience initializer must ultimately call a designated initializer from the same class.

Above rules can be summed up in below points:

  1. A designated initializer must always delegate up in the class hierarchy.
  2. A convenience initializer must delegate across the same class.
class RecipieIngridient : Food{
    var quantity : Int
    init(name : String, quantity : Int){
self.quantity = quantity
//delegates up to super class designated initializer
super.init(name: name)
    //matches superclass designated initializer init(name:), so need   to override
    convenience override init(name : String){
//delegates across to own designated initializer
//convenience initializer cannot delegate up to superclass initailizer
self.init(name : name, quantity: 1)

Automatic initializer inheritance

If subclasss does not provide any designated initializers, all superclass designated and convenience initializers are automatically inherited.

class ShoppingListItem : RecipieIngridient{
var purchased = false
var items = [ShoppingListItem(),
ShoppingListItem(name : “Bacon”),
ShoppingListItem(name:”Eggs”, quantity: 6)]

That’s all for initializer delegation in classes. Please recommend if you liked this post.

Show your support

Clapping shows how much you appreciated Anutosh Datta’s story.