Swift : Why super.init Is Called After setting all self Properties
The Swift Programming Language says a lot about class initializations. Classs objects are initialised in two phases.
In the first phase, each stored property is assigned an initial value by the class that introduced it. Once the initial state for every stored property has been determined, the second phase begins, and each class is given the opportunity to customize its stored properties further before the new instance is considered ready for use.
So there are few (four to be exact) safety checks to make sure two phase intiliazations happen as expected. Here what the first safety check says.
Safety check 1
A designated initializer must ensure that all of the properties introduced by its class are initialized before it delegates up to a superclass initializer.
And the question arises why. Its reverse of what we used to do in Objective-C, so, Why do I need to call super.init, after all of the property introduceted by this class are initialized? At first observation it seems it would have hardly made a difference if called at first or at last.
Lets see and example,
Here if we had called the
super.init before setting the
super.init call would then have called the
printShapeDescription() and since that has been overridden it would first fallback to Triangle class implementation of
printShapeDescription() of Triangle class access the
hypotenuse a non optional property that still has not been initialised. And this cannot happen as all the non optional properties of a class need to be initialised before being accessed.
Hence Saftey check 1 makes a lot of sense now.