0Pricing
Swift Academy · Lesson

Computed properties with get/set

Create computed properties (read-only and read–write) using get/set, enforce invariants in setters, and use access control like private(set).

Overview

Computed properties derive values on access and can synchronize state on set. Use them to keep invariants tidy.

Read-only computed

A read-only computed property omits set. Keep derivations simple and cheap.

struct Rectangle {
    var width: Double
    var height: Double
    var area: Double {             // read-only computed
        width * height
    }
}
let r = Rectangle(width: 3, height: 4)
print("area =", r.area)  // 12

All lessons in this course

  1. Properties & Subscripts
  2. lazy & property observers
  3. Computed properties with get/set
  4. Subscripts for custom indexing
← Back to Swift Academy