accessor╱getter/setter╱🚧 -> keyword "let"
Last updated 3 months ago
Was this helpful?
Swift ⟩ type ⟩ property ⟩ computed property
stored vs. computed
屬性沒有實際儲存的值,值是動態計算的。
computed property 的優勢:
get :可動態計算並傳回屬性值。
get
set :可攔截屬性變更,檢查或調整其值,保護內部狀態。
set
willSet/didSet vs. get/set
computed property 也稱為 accessor。
computed property 一定要用 var 宣告。
var
struct Circle { var radius: Double // ⭐️ computed property var area: Double { .pi * radius * radius } // ⭐️ (implicit) get only } // 利用 computed property 來確保屬性值的範圍 struct NoLessThanThree { // inner state private var _value: Int = 3 // ⭐️ computed property var value: Int { get { _value } set { _value = max(newValue, 3) } // 確保數值不小於 3 } } // 註:如果初始化後屬性值就不變,可考慮以下做法: struct Example { // (stored property) private set/internal get (get OK/no set!) private(set) var value: Int init(value: Int) { self.value = max(value, 3) // 確保數值不小於 3 } }
📁 測試
// 測試 var num = NoLessThanThree() num.value = 5 num.value = 2 // value 被 setter 調整為 3 ⭐️ print(num.value) // 3
Computed properties in Swift: A basic feature for safer and cleaner code
Develop with Swift ⟩ Customize views with properties
local computed variables
mutating getter / nonmutating setter
property observer (willSet/didSet): you can add in computed properties that you inherit.
Swift ⟩ Properties ⟩
Stored Properties
Computed Properties