Search code examples
iosswiftinheritancesubclasssuperclass

how is the subclass property "quantity" initialised


I'm trying to learn the concept of inheritance and initialisation in swift and have came up with the following code. "the swift programming language 2.1" states that if a subclass provides implementation of all of its superclass's designated initialiser, the subclass also automatically inherits all of its superclass convenience initialisers too.

Therefore the subclass "RecipeIngredient" should have inherited superclass "Food"'s convenience init(){ self.init(name: "[unnamed]"). But this particular convenience init only initialise the var name, how can it initialise the subclass property quantity? Could someone please explain it to me, how is the subclass property quantity initialised when I create an instance of subclass using the superclass convenience init(){ self.init(name: "[unnamed]")? Thanks in advance for any help!

class Food {
    var name: String
    init(name: String){
        self.name = name
    }
    convenience init() {
        self.init(name: "[unnamed]")
    }

}




class RecipeIngredient: Food{
    var quantity: Int
    init(name: String, quantity: Int){
        self.quantity = quantity
        super.init(name: name)
    }

    override convenience init(name: String){
        self.init(name: name, quantity: 1)
    }
}


let ingredientOne = RecipeIngredient()
ingredientOne.name
ingredientOne.quantity

Solution

  • When you execute

    let ingredientOne = RecipeIngredient()
    

    the method Food.init() runs, and calls self.init(name:String). self is actually an instance of RecipeIngredient, so this method is actually RecipeIngredient.init(name:String) which you have provided to initialise the quantity.

    It's possible to confirm this by putting a print statement at each of the init routines to see which methods are called in which order.

    If I comment out the method RecipeIngredient.init(name:String) the compiler will no longer let me write RecipeIngredient().