property observer (willSet/didSet)
╱🚧 under construction ->
Last updated
╱🚧 under construction ->
Last updated
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.