Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Build a Simple iPhone App with Swift Getting Started with iOS Development Recap of Object Oriented Swift

Gene Bogdanovich
Gene Bogdanovich
14,618 Points

Initializing a Subclass

In the Object Oriented Swift 3 course in the lesson called Overriding Properties instructor said that when we're initializing a subclass we first need to provide values for properties of the subclass, but in the Build a Simple iPhone App with Swift 3 course in the quiz called Recap of Object Oriented Swift one of the quiz's questions says "When we initialize a subclass, we first need to initialize the properties in our base class, then call the super class' initializer". So what do we need to do first? Provide values for properties of the base class or the subclass?

Thanks for any help!

1 Answer

Chris Stromberg
PLUS
Chris Stromberg
Courses Plus Student 13,389 Points

There is a good explanation of what you are asking here regarding two-phase initialization.

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html

From the apple docs:

Swift’s compiler performs four helpful safety-checks to make sure that two-phase initialization is completed without error:

A designated initializer must ensure that all of the properties introduced by its class are initialized before it delegates >up to a superclass initializer.

As mentioned above, the memory for an object is only considered fully initialized once the initial state of all of its stored properties is known. In order for this rule to be satisfied, a designated initializer must make sure that all of its own properties are initialized before it hands off up the chain. "