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.

Tip

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.

Tip

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 to have a value initialized to the appropriate values that represent the shape. Initializers are extremely useful when we want to define the values for the properties of the instances of a class right after their creation and before we can access the variables that reference the created instances.

Sometimes, we need specific arguments to be available at the time of creating an instance. We can design different initializers with the necessary arguments and use them to create instances of a class. This way, we can make sure that there is no way of creating specific classes without using the provided initializers that make the necessary arguments required.

Swift uses a two-phase initialization process for classes. The first phase makes each class in the hierarchy that defines a property assign the initial value for each of them. Once all the properties are assigned their initial values, the second phase allows each class in the hierarchy to customize each of its defined properties. After the second phase finishes, the new instance is ready to be used, and Swift allows us to access the variable that references this instance to access its properties and/or call its methods.

Tip

In case you have experience with Objective-C, the two-phase initialization process in Swift is very similar to the procedure in Objective-C. However, Swift allows us to set customized initial values.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.60.232