Computed properties with get/set
Create computed properties (read-only and read–write) using get/set, enforce invariants in setters, and use access control like private(set).
Overview
Computed properties derive values on access and can synchronize state on set. Use them to keep invariants tidy.
Read-only computed
A read-only computed property omits set. Keep derivations simple and cheap.
struct Rectangle {
var width: Double
var height: Double
var area: Double { // read-only computed
width * height
}
}
let r = Rectangle(width: 3, height: 4)
print("area =", r.area) // 12All lessons in this course
- Properties & Subscripts
- lazy & property observers
- Computed properties with get/set
- Subscripts for custom indexing