Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Object-Oriented Swift Inheritance Convenience Initializers

bogdan barbulescu
PLUS
bogdan barbulescu
Courses Plus Student 232 Points

Delegate to SuperClass before initializing inherited properties

Am I right saying that when a property is inherited in a subclass, we have to delegate to a SuperClass designated initializer in order to avoid the case in which the designated initializer from the SuperClass would overwrite our property? Is this event happening due to the fact that classes are reference types and not value types.

class myVehicle{


var numberOfWheels = 0
var description: String {
    return "\(numberOfWheels) wheel(s)"
    }
}

let vehicle = myVehicle()
print(vehicle.description)


class myBicycle: myVehicle {

override init(){

super.init()
numberOfWheels = 2

    }
}

let someBicycle = myBicycle()
print(someBicycle.numberOfWheels)

My understanding is that this code works in the following way. Let me know if I have understood it right.

  1. We are creating an instance of myBicycle() and the initializer from myBicycle subclass is called.
  2. Memory is allocated to create the instance.
  3. The overriden designated initializer init() ensures all stored properties introduced by the subclass ( there are none) are assigned/are initialized with an initial value.
  4. The overriden designated initializer init() now calls super.init()
  5. super.init() basically delegates to the SuperClass default initializer ( which is at all times a designated initializer)
  6. The default initializer from the SuperClass initializes its only stored property introduced by the class , var numberOfWheels = 0
  7. The memory of myBicycle() instance is considered fully initialized and each class is given the opportunity to further customize its properties, access self...etc.
  8. The computed description property returns a string
  9. The customization moves down the chain to the subclass myBicycle
  10. numberOfWheels inherited property is initialized with a value of 2 by override init() initializer.