#52: Computed Properties with get and set

Computed properties let you present a value that is derived from other stored properties instead of duplicating state.

struct Rectangle {
    var width: Double
    var height: Double

    var area: Double {
        get { width * height }
        set { width = sqrt(newValue); height = sqrt(newValue) }
    }
}

In practice, many computed properties only need a getter:

var perimeter: Double { 2 * (width + height) }

They are a good fit for values that should always stay in sync with your real source of truth.


I'm also on Twitter and GitHub.

Subscribe via RSS.