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

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.

主站蜘蛛池模板: 嘉鱼县| 通州市| 德保县| 体育| 桂平市| 高邮市| 乌鲁木齐市| 华亭县| 府谷县| 北京市| 滨州市| 德保县| 江安县| 清苑县| 曲沃县| 敦化市| 溧阳市| 南城县| 仁化县| 徐州市| 巴彦淖尔市| 娱乐| 陇西县| 宁明县| 增城市| 吉林市| 灵石县| 剑阁县| 黑龙江省| 台北县| 蒙城县| 哈密市| 万安县| 新邵县| 时尚| 舒城县| 罗城| 夏邑县| 清原| 潼南县| 肃宁县|