Notes for swift language 11 (willSet and didSet) and willsetdidset
The willSet and didSet features are used in Swift to monitor attribute value changes except initialization.
You don't need to talk too much. You can quickly understand the following code.
Copy code
Import Foundation
Class People: NSObject
{
// Common attributes
Var firstName: String = ""
Var lastName: String = ""
Var nickName: String = ""
// Calculate the property var fullName: String {get {return nickName + "" + firstName + "" + lastName }}// common property var age with property monitor: int = 0 {// What do we need to do before the age attribute changes willSet {println ("Will set an new value \ (newValue) to age ")} // After the age attribute changes, update the didSet {println ("age filed changed form \ (oldValue) to \ (age)") attribute of nickName )") if age <10 {nickName = "Little"} else {nickName = "Big" }}} func toString ()-> String {return "Full Name: \ (fullName) "+", Age: \ (age )"}
}
Var me = People ()
Me. firstName = "Zhang"
Me. lastName = "San"
Me. age = 20
Println (me. toString ())
/* Program output
Will set an new value 20 to age
Age filed changed form 0 to 20
Full Name: Big Zhang San, Age: 20
*/
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.