๐ŸŽ“ A1Learner
๐Ÿ”
0 of 36 lessons completed

Swift Computed Properties

A computed property is a property that works out its value when it is read instead of storing one. Its get block holds the code that builds the value.

An area worked out on each read

The Rectangle struct stores a width and a height. The area property multiplies them inside its get block every time it is read.

struct Rectangle {
    var width: Int
    var height: Int
    var area: Int {
        get {
            return width * height
        }
    }
}
let rect = Rectangle(width: 4, height: 5)
print(rect.area)
print(rect.width)

A reading in another unit

The temperature stores only its Celsius value. The fahrenheit property converts that stored value inside its get block.

struct Temperature {
    var celsius: Double
    var fahrenheit: Double {
        get {
            return celsius * 9.0 / 5.0 + 32.0
        }
    }
}
let day = Temperature(celsius: 25.0)
print(day.celsius)
print(day.fahrenheit)

Writing back through set

Assigning to fahrenheit runs its set block with the assigned value in newValue. The set block converts that value and stores it in celsius.

struct Temperature {
    var celsius: Double
    var fahrenheit: Double {
        get {
            return celsius * 9.0 / 5.0 + 32.0
        }
        set {
            celsius = (newValue - 32.0) * 5.0 / 9.0
        }
    }
}
var day = Temperature(celsius: 20.0)
print(day.fahrenheit)
day.fahrenheit = 104.0
print(day.celsius)

Example

struct Wheel {
    var radius: Int
    var diameter: Int {
        get {
            return radius * 2
        }
        set {
            radius = newValue / 2
        }
    }
}
var wheel = Wheel(radius: 7)
print(wheel.diameter)
wheel.diameter = 30
print(wheel.radius)

Key points

  • A computed property stores no value of its own.
  • The get block runs each time the property is read.
  • A computed property with only a get block can be read but not assigned.
  • A set block runs when a value is assigned to the property.
  • Inside the set block, newValue holds the assigned value.
  • The set block usually writes its result back into stored properties.

In this example, the Wheel struct stores a radius of 7. The get block of diameter doubles the radius, so the first print shows 14. Assigning 30 to diameter runs the set block, which halves newValue and stores 15 in radius, so the last print shows 15.

Note

Reading a computed property twice runs its get block twice.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Inside the set block of a computed property, which name holds the value that was just assigned?