← Back to Swift Course | Chapter 8: Structs & Classes | Lesson 5 of 9

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

markup
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)")

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

markup
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)")
Common Mistakes
  1. Trying to store a value directly into a read-only computed property (one with only a get); it has no backing storage at all.
  2. Forgetting a computed property needs an explicit type annotation, since there's no initial value for Swift to infer from.
  3. 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 get block each time it's accessed.
  • An optional set block lets a computed property also be assigned to.
  • Computed properties are declared with var, never let, 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.