官术网_书友最值得收藏!

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 CalculateArea or CalculatePerimeter 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 we create 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 value, 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.

主站蜘蛛池模板: 武平县| 郑州市| 广宗县| 鄂托克前旗| 蕲春县| 通许县| 松桃| 潍坊市| 姜堰市| 军事| 隆回县| 红河县| 多伦县| 卢氏县| 乐东| 垦利县| 新蔡县| 宾川县| 鸡泽县| 通辽市| 乡宁县| 满洲里市| 汕尾市| 湖南省| 砚山县| 务川| 屏南县| 邓州市| 吉安市| 扶沟县| 焦作市| 都江堰市| 南宁市| 临颍县| 宜阳县| 五峰| 建水县| 建阳市| 石景山区| 广西| 南城县|