標籤:swift willset didset
在Swift語言中用了willSet和didSet這兩個特性來監視屬性的除初始化之外的屬性值變化
無需說太多,看看下面的代碼你就能很快明白的
複製代碼
import Foundation
class People : NSObject
{
//普通屬性
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())
/*程式輸出
Will set an new value 20 to age
age filed changed form 0 to 20
Full Name: Big Zhang San , Age: 20
*/
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
swift語言的學習筆記十一(willSet與didSet)