🔸property observer (willSet/didSet)
╱🚧 under construction ->
Swift ⟩ type ⟩ property ⟩ stored ⟩ property observer
只需監控屬性變化或執行副作用,用 willSet/didSet (property observer)
需主動調整或限制屬性值時,用 get/set。
willSet:在變更前的準備工作,如:檢查、備份舊值或發出警告。
didSet:監控變更後的處理,如:限制範圍、觸發事件或更新 UI。
willSet 無法阻止或改變屬性值的設定,但 didSet 可進行修正。
willSet/didSet 是給 stored property 用的,computed property 不能用❗
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:
stored properties that you define╱inherit.
computed properties that you inherit.
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?