代碼以下: swift
class People: NSObject { // 普通屬性 var firstName : String = "" var lastName : String = "" var nickName : String = "" // 計算屬性 var fullName : String { get{ return nickName + "" + firstName + "" + lastName } } // 帶屬性監視器的普通屬性 var age: Int = 0 { // 咱們須要在get 屬性變化前作點什麼 willSet { print("給age從新賦值\(newValue) to age") } // 咱們須要在age 屬性發生變化後,更新一下nickName 這個屬性 didSet { print("age 從 \(oldValue) 改變成 \(age)") if age < 10 { nickName = "看我多小" }else{ nickName = "看我多大" } } } func toSting() -> String { return "fullName:\(fullName) + Age:\(age)" } } var me = People() me.firstName = "張" me.lastName = "四" me.age = 20 print(me.toSting())