Skip to content
Tutorials Center
My learning

Topics

Lesson 60 of 146 ยท Structures, Classes and Enums

Lazy Properties and Property Observers

Learn Swift lazy properties and property observers in depth - when lazy runs, lazy in structs, thread safety, willSet and didSet order, oldValue, observers in init and subclasses.

The properties lesson introduced lazy var, willSet and didSet in a few lines. They deserve a closer look, because both features have rules that surprise people: a lazy property is computed at a moment you do not control, a property observer is silently skipped in some places, and both behave differently in structs and classes.

This lesson answers the questions that come up in real code. When exactly does a lazy initializer run? Why does reading a lazy property from a constant struct fail? In what order do willSet and didSet run, and why does an observer not fire inside init? By the end you will know when each tool is the right one and when a computed property or a plain method is better.

What lazy does

A lazy stored property has an initial value that is not calculated until the first time something reads the property. You mark it with lazy var and give it a default value (often a closure call or an expensive initializer).

Swift
lazy var report = makeReport()

Nothing runs when the owner is created. The first read runs the initializer and stores the result; every later read returns the stored value without running the initializer again.

stateDiagram-v2
    [*] --> NotComputed: instance created
    NotComputed --> Stored: first read runs the initializer
    Stored --> Stored: later reads return the stored value
    Stored --> Stored: assigning replaces the value

A lazy property is "empty" until the first read, then it behaves like an ordinary stored property.

Swift Lazy runs once, on first use

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The creation message prints first, then nothing builds until board.summary is read. The "building" line appears exactly once, between the first two lines of output. Because a lazy property is a normal var, you can also assign to it; the initializer is then never needed.

Why the initializer may use self

An ordinary stored property cannot refer to other properties or to self in its default value, because the instance does not exist yet when defaults are evaluated. A lazy property can, because it runs after initialization is complete. That is why owner could be used inside the closure above.

Swift
class Wrong {
    let base = 10
    var doubled = base * 2          // error: cannot use instance member 'base'
    lazy var tripled = base * 3     // fine
}

Use this when a value depends on other properties but you do not want to pay for it unless somebody asks.

Lazy needs var

A lazy property has to be var, because it starts "empty" and is filled in later, which is a mutation. Declaring it with let is rejected. Try it.

Swift lazy let is not allowed (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler reports that 'lazy' cannot be used on a let. Switch to lazy var to fix it.

Lazy in structs and constants

In a class, reading a lazy property from a let constant works, because a class instance can change its stored properties even when the reference is constant. In a struct, filling in the lazy value changes the struct, so reading it requires a var. This surprises people because the code only "reads".

Swift A lazy struct property needs a variable (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The error is cannot use mutating getter on immutable value: 'fixed' is a 'let' constant. The getter of a lazy property in a struct is mutating, so the value must be declared with var. If you want a constant struct with an expensive derived value, either compute it in init, use a plain computed property, or make the type a class.

A lazy property is not thread-safe. If two threads read it for the first time at the same moment, the initializer can run twice. When a type is shared across tasks, compute the value in init, or protect the type with an actor. Global variables and static properties are different: the language initializes those lazily and safely for you.

Global variables and static let properties are always lazily initialized, and Swift guarantees that happens once and safely. You do not write lazy on them. You only need the lazy keyword for instance properties.

When to choose something else

Lazy is the right tool when the value is expensive, depends on other properties, and never needs to change when they change. If the value must follow other properties, use a computed property instead, because a lazy value is computed once and goes stale:

Swift Lazy goes stale, computed does not

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The lazy value stays 12.0 after the width changes, while the computed property correctly reports 40.0. Remember this rule: lazy remembers, computed recalculates.

Property observers

An observer runs your code when a stored property is set. There are two:

  • willSet runs just before the new value is stored. Inside it, the incoming value is newValue (or a name you choose).
  • didSet runs just after the new value is stored. Inside it, the previous value is oldValue (or a name you choose).
flowchart LR
    A["x = 5"] --> B["willSet<br/>newValue is 5"]
    B --> C["store 5"]
    C --> D["didSet<br/>oldValue is the previous value"]

An assignment runs willSet, then stores the value, then runs didSet.

Swift The order of willSet and didSet

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Notice that setting the same value 23 twice still triggers both observers the second time. Swift does not compare old and new values; if you only care about real changes, compare them yourself with guard oldValue != target else { return }.

You can rename the parameters, which often reads better:

Swift
var score = 0 {
    willSet(incoming) { print("will become \(incoming)") }
    didSet(previous)  { print("was \(previous)") }
}

Common uses: clamping and syncing

The most useful pattern is to fix up a value after it is set. Assigning to the same property inside its own didSet does not call the observers again, so there is no infinite loop.

Swift Clamping a volume in didSet

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The assignment of 40 is corrected to 10 and then -3 to 0. The print shows the final, corrected value. For a bounded value you reuse in many places, a property wrapper is cleaner than copying this didSet everywhere.

Observers do not run during initialization

Setting a property inside its own type's init does not call its observers, and neither does a default value. That is deliberate: during init the instance is not fully formed. The observers run for assignments made after initialization finishes.

Swift Observers are skipped in init

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

There is no output from didSet during init. The += 1 and the call to reset() both fire it. If you need the clamping or syncing logic during init as well, call a method from init, or write the logic in a function and use it in both places.

Structs: changing a part changes the whole

For a struct stored in a property, changing a field of it counts as setting the whole property, because a struct is one value. So the observer fires even though you only touched x.

Swift Observers on a struct property

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Each field assignment prints one line with the full old and new Point. With a class instance stored in the property, changing a field of that object would not fire the observer, because the reference itself did not change. See value vs reference for the reason.

Observers and inheritance

A subclass can add observers to an inherited stored or computed property by overriding it, without knowing how the superclass stores it. When both classes observe the property, the superclass observers run too, and the order is: subclass willSet, then superclass willSet, then the store, then superclass didSet, and finally the subclass didSet.

Swift Observers in a subclass

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The four lines print from the subclass willSet outward, then back out. You can only add observers to a property in a subclass; you cannot remove the superclass behavior. A let constant cannot have observers, and a computed property does not need them because you already write its set body. See inheritance for the rest of overriding.

Choosing between the tools

You want Use
An expensive value computed only when first needed lazy var
A value that always reflects other properties computed property
React to every change, or validate and clamp willSet / didSet
Reuse the same clamp/validation across types a property wrapper
Notify many other objects @Observable (see Observation)

If you do not mention oldValue in didSet, Swift does not even fetch the old value, which saves work for large collections. Only reference oldValue when you need it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When does the initializer of a lazy property run?

    A lazy property stays empty until the first read, then stores the result. Later reads reuse the stored value.
  2. 2. Why can a lazy property's default value use other properties through self?

    Ordinary defaults are evaluated before the instance exists, so they cannot use self. A lazy default runs later, when the instance is complete.
  3. 3. What happens if you read a lazy property from a struct stored in a let constant?

    In a struct, filling in the lazy value is a mutation, so the value must be declared with var.
  4. 4. Which sequence is printed for x = 5 when a property has both observers?

    willSet runs before the new value is stored; didSet runs after, with oldValue holding the previous value.
  5. 5. Is didSet called when you set the property inside the type's own init?

    Assignments made in init (and default values) do not trigger observers; later assignments do.

Summary

  • A lazy var runs its initializer once, on first read, and then behaves like a stored property.
  • Lazy defaults may use self; they must be var; they can go stale, so use a computed property when the value must follow others.
  • A lazy property in a struct needs a var owner and is not thread-safe.
  • willSet runs before the store (newValue), didSet after it (oldValue); assigning to the property inside its own didSet does not recurse.
  • Observers are skipped during init, fire even for equal values, and fire for field changes of a struct property.
  • A subclass can add observers by overriding; the order is subclass willSet, superclass willSet, store, superclass didSet, subclass didSet.

Next: Protocols