AnyCompiler

Properties

A computed property has no storage of its own — its value is calculated fresh every time it's read, from a getter block. fahrenheit below never stores anything; it recomputes from celsius on every access.

struct Temperature {
    var celsius: Double
    var fahrenheit: Double {
        return celsius * 9.0 / 5.0 + 32.0
    }
}
let t = Temperature(celsius: 100)
print(t.fahrenheit)
Output
212.0

A property observer, by contrast, does have real storage, but runs extra code automatically around an assignment. didSet runs right after the new value has been set — useful for reacting to a change without the caller having to remember to call anything themselves.

class Thermostat {
    var temperature: Int = 70 {
        didSet {
            print("Temperature set to \(temperature)")
        }
    }
}
let thermo = Thermostat()
thermo.temperature = 75
Output
Temperature set to 75

Next: inheritance — class-only inheritance, and overriding a method with override.

Practice exercise

Define a struct named Temperature with var celsius: Double and a computed property fahrenheit: Double that returns celsius * 9.0 / 5.0 + 32.0. Create let t = Temperature(celsius: 100) and print t.fahrenheit.