🔰computed property (get/set)
accessor╱getter/setter╱🚧 -> keyword "let"
Swift ⟩ type ⟩ property ⟩ computed property
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
}
}📁 測試
property observer (willSet/didSet): you can add in computed properties that you inherit.
Swift ⟩ Properties ⟩
Last updated
Was this helpful?