🔰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
}
}
📁 測試
// 測試
var num = NoLessThanThree()
num.value = 5
num.value = 2 // value 被 setter 調整為 3 ⭐️
print(num.value) // 3
Last updated
Was this helpful?