🔸property observer (willSet/didSet)

╱🚧 under construction ->

Swifttypepropertystored ⟩ property observer

  • Property observers are called every time a property’s value is set, even if the new value is the same as the property’s current value.

    • willSet is called just before the value is stored.

    • didSet is called immediately after the new value is stored.

  • You can add property observers in the following places:

struct Example {
    
    // ⭐️ stored property
    var value: Int = 0 {
    
        // ⭐️ property observer examples
        
        willSet {
            // ⭐️ willSet 隱含一個 newValue 變數,指即將要變更的新屬性值
            print("value 即將被設定為 \(newValue)")
        }
        
        // ---------------------------------------
        
        // 狀況一:只做紀錄,不做任何修改
        didSet {
            // ⭐️ didSet 隱含一個 oldValue 變數,用來存取舊的屬性值
            print("value 從 \(oldValue) 改為 \(value)")
        }
        
        // 狀況二:除了監控外,再做修改
        // (如果是這種情況,可考慮用 computed property (get/set))
        didSet {
            if value < 3 {
                print("value 小於 3,自動調整為 3")
                // ⭐️ didSet 內可重新設定屬性值,
                // ❗️ 但不會再觸發 didSet,以免無限循環。
                value = 3
            }
        }
        
    }// value
}

Last updated

Was this helpful?