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

How it works...

Defining a struct is very similar to defining an object class, and that is intentional. Much of the functionality available to a class is also available to a struct.

Within the PersonName struct, we have properties for the three components of the name and the fullName method we saw earlier to combine the three name components into a full name string.

Next, we have a method to change the family name property, which is why we defined the familyName property as a var variable instead of a let constant. This method assigns a new value to a property of the struct; it is mutating, or changing, the struct, and therefore needs to be marked with the mutating keyword. This keyword is enforced by the compiler to remind us that when we mutate a struct, a new copy of the original struct is created with the new value. This is known as value-type semantics.

To see this in action, consider the following code:

let alissasBirthName = PersonName(givenName: "Alissa", middleName: "May", familyName: "Jones") 
print(alissasName.fullName()) // Alissa May Jones
var alissasCurrentName = alissasBirthName
print(alissasName.fullName()) // Alissa May Jones

So far, so good. We have created a PersonName struct and assigned it to a constant called alissasBirthName and a variable called alissasCurrentName.

When we change or "mutate" the alissasCurrentName variable, only this variable is changed; alissasBirthName is a copy, and so it doesn't have the amended family name, even though they were assigned from the same source:

alissasCurrentName.change(familyName: "Moon") 
print(alissasBirthName.fullName()) // Alissa May Jones
print(alissasCurrentName.fullName()) // Alissa May Moon
主站蜘蛛池模板: 长阳| 龙里县| 灵丘县| 鄂托克旗| 阳春市| 柯坪县| 皮山县| 长兴县| 蓬溪县| 色达县| 宁城县| 淄博市| 阳新县| 桐柏县| 烟台市| 海门市| 青阳县| 磐安县| 二连浩特市| 静乐县| 河东区| 台北市| 宁远县| 偃师市| 西畴县| 隆回县| 乡宁县| 霍城县| 渑池县| 油尖旺区| 开封县| 定边县| 徐州市| 马关县| 永泰县| 饶平县| 定兴县| 吉安市| 兴隆县| 清新县| 买车|