- Swift 4 Programming Cookbook
- Keith Moon
- 258字
- 2021-07-08 10:21:26
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
- Qt 5 and OpenCV 4 Computer Vision Projects
- PowerCLI Cookbook
- JavaScript 網(wǎng)頁編程從入門到精通 (清華社"視頻大講堂"大系·網(wǎng)絡(luò)開發(fā)視頻大講堂)
- Visual C++數(shù)字圖像處理技術(shù)詳解
- HTML5入門經(jīng)典
- H5頁面設(shè)計(jì):Mugeda版(微課版)
- Linux:Embedded Development
- RabbitMQ Essentials
- C/C++程序員面試指南
- Android項(xiàng)目實(shí)戰(zhàn):手機(jī)安全衛(wèi)士開發(fā)案例解析
- C/C++數(shù)據(jù)結(jié)構(gòu)與算法速學(xué)速用大辭典
- Struts 2.x權(quán)威指南
- WCF全面解析
- H5匠人手冊(cè):霸屏H5實(shí)戰(zhàn)解密
- C#程序開發(fā)參考手冊(cè)