5.7 Analysis of set and get methods of class properties [Swift original tutorial]

Original: http://coolketang.com/staticCoding/5a9925ad9f5454507417fc90.html

1. The get and set keywords are known as computed properties. Its purpose is to execute the code inside when taking and assigning values. This lesson will teach you how to use these two keywords. 



2. First define a class with a specified name, as the game player. 


3. Then add a name attribute to the class and set its default value. 


4. Add another level property and set its default value. 


5. Add a third attribute as the player's score, and add a pair of braces at the end to add the code that needs to be executed. 


6. First add a get statement, when getting the value of the score, return the product of the player's level and 2. 


7. Then add a set statement. When setting the value of the score, it also sets the player's level attribute. 


8. After creating the type, instantiate an object of the class. 


9. Then obtain the score attribute of the object. At this time, it can be seen from the real-time feedback result on the right that the value of the score is 6. 


10. Then set the player object's score to 4. 


11. At this time, the level of the player object has also changed, and the value of the level attribute has been changed from the default value of 3 to 2. 


This article is organized from: "Swift4 Interactive Tutorial", the real [Hands-on] teaching mode, get started with iOS development and Swift language at the fastest speed, free download from Apple Store App Store: https://itunes.apple.com/cn/app/id1320746678 , or scan the QR code at the bottom of this page . Course supporting material download address: data download


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325382925&siteId=291194637