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.
Syntax
struct TypeName {
var computed: Type {
get { return value }
set { /* use newValue */ }
}
var readOnly: Type { return value }
}
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
// Define a struct `Rectangle`
struct Rectangle {
var width: Double
var height: Double
var area: Double {
// Return `width * height` from this function
return width * height
}
}
// Declare a constant `rect`, set to `Rectangle(width: 4, height: 5)`
let rect = Rectangle(width: 4, height: 5)
// Print "Area: \(rect.area)" to the console
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
// Define a struct `Temperature`
struct Temperature {
var celsius: Double
var fahrenheit: Double {
get { celsius * 9 / 5 + 32 }
set { celsius = (newValue - 32) * 5 / 9 }
}
}
// Declare a mutable variable `temp`, initialized to `Temperature(celsius: 0)`
var temp = Temperature(celsius: 0)
// Print "Fahrenheit: \(temp.fahrenheit)" to the console
print("Fahrenheit: \(temp.fahrenheit)")
temp.fahrenheit = 212
// Print "Celsius after setting F: \(temp.celsius)" to the console
print("Celsius after setting F: \(temp.celsius)")
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
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: