The Willset and Didset features are used in the swift language to monitor property value changes other than initialization of properties
There's no need to say too much, just look at the code below and you'll get it quickly.
Copy Code
Import Foundation
Class People:nsobject
{
Normal properties
var firstname:string = ""
var lastname:string = ""
var nickname:string = ""
//计算属性var fullName:String{ get { return nickName + " " + firstName + " " + lastName }}//带属性监视器的普通属性var age:Int = 0{ //我们需要在age属性变化前做点什么 willSet { println("Will set an new value \(newValue) to age") } //我们需要在age属性发生变化后,更新一下nickName这个属性 didSet { println("age filed changed form \(oldValue) to \(age)") 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
Would set an new value
Age filed changed form 0 to 20
Full Name:big Zhang San, age:20
*/
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Learning note for Swift language 11 (Willset and Didset)