Computed Properties
A computed property doesn't store a value at all -- it calculates one fresh every time you ask for it, like a thermometer showing the current temperature.
Read-Only Computed Property
A computed property with only a get block calculates and returns its value on every access, without storing anything.
Example: Read-Only Computed Property
struct Rectangle {
var width: Double
var height: Double
var area: Double {
return width * height
}
}
let rect = Rectangle(width: 4, height: 5)
print("Area: \(rect.area)")
Login to try C/C++/Java/PHP code in the editor
Computed Property with get and set
Adding a set block lets you assign to a computed property, typically translating the new value into changes on the underlying stored properties.
Example: Computed Property with get and set
struct Temperature {
var celsius: Double
var fahrenheit: Double {
get { celsius * 9 / 5 + 32 }
set { celsius = (newValue - 32) * 5 / 9 }
}
}
var temp = Temperature(celsius: 0)
print("Fahrenheit: \(temp.fahrenheit)")
temp.fahrenheit = 212
print("Celsius after setting F: \(temp.celsius)")
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Trying to store a value directly into a read-only computed property (one with only a
get); it has no backing storage at all. - Forgetting a computed property needs an explicit type annotation, since there's no initial value for Swift to infer from.
- Writing expensive logic inside a computed property's getter that runs repeatedly on every access, when a stored, precalculated value might be more efficient.
Chapter Summary
- A computed property calculates its value with a
getblock each time it's accessed. - An optional
setblock lets a computed property also be assigned to. - Computed properties are declared with
var, neverlet, since they aren't stored values. - They're useful for values derived from other properties.
🔒
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: