屬性觀察員

屬性觀察員迴應房產價值的變化。

var myProperty = 5 {
    willSet {
        print("Will set to \(newValue). It was previously \(myProperty)")
    }
    didSet {
        print("Did set to \(myProperty). It was previously \(oldValue)")
    }
}
myProperty = 6
// prints: Will set to 6, It was previously 5
// prints: Did set to 6. It was previously 5
  • 設定 myProperty 之前呼叫 willSet。新值以 newValue 的形式提供,舊值仍可作為 myProperty 使用。
  • 設定 myProperty 呼叫 didSet。舊值可用作 oldValue,新值現在可用作 myProperty

注意: 在下列情況下不會呼叫 didSetwillSet

  • 分配初始值
  • 在自己的 didSetwillSet 中修改變數
  • didSetwillSetoldValuenewValue 的引數名稱也可以宣告為增加可讀性:
var myFontSize = 10 {
    willSet(newFontSize) {
        print("Will set font to \(newFontSize), it was \(myFontSize)")
    }
    didSet(oldFontSize) {
        print("Did set font to \(myFontSize), it was \(oldFontSize)")
    }
}

警告: 雖然支援宣告 setter 引數名稱,但是應該小心不要混淆名稱:

  • willSet(oldValue)didSet(newValue) 完全合法,但會使讀者對你的程式碼感到非常困惑。