Understanding initialization and its customization
When you ask Swift to create an instance of a specific class, something happens under the hood. Swift creates a new instance of the specified type, allocates the necessary memory, and then executes the code specified in the initializer.
Note
You can think of initializers as equivalents of constructors in other programming languages such as C# and Java.
When Swift executes the code within an initializer, there is already a live instance of the class. Thus, we have access to the properties and methods defined in the class. However, we must be careful in the code we put in the initializer because we might end up generating huge delays when we create instances of the class.
Note
Initializers are extremely useful to execute setup code and properly initialize a new instance.
So, for example, before you can call either the calculatedArea
or calculatedPerimeter
method, you want both the semiMajorAxis
and semiMinorAxis
fields for each new Ellipse
instance...