In Swift, what does marking a stored property lazy do, and why must a lazy property be declared with var?
answer
- first access, not initialization
- a let must be set during init
- a mutating getter on structs
- no once-only guarantee across threads
basics
~20 sA lazy stored property runs its initial-value expression on first access instead of during initialization, then keeps the result. It must be var because it gets its value after initialization ends, which a let constant cannot do.
solid answer
~50 s`lazy var` defers a stored property's initial value until the first read; after that the stored result is returned and **never recomputed**, even if the values it was built from change. It must be `var` because a `let` must have its value before initialization completes, and `lazy let` is the error "'lazy' cannot be used on a let". Because the initializer runs after `init`, it may use `self`. On a struct the first read writes storage, so the getter is mutating: reading it through a `let` instance fails with "cannot use mutating getter on immutable value". Assigning before the first read means the initializer never runs. The book is explicit that if several threads read an uninitialized lazy property at once, there is no guarantee it is initialized only once; stored `static` properties, by contrast, are lazy and initialized only once without the keyword.
code
swift · 17 linesstruct TemperatureLog {
var readings: [Double]
lazy var average: Double = {
print("computing average")
return readings.reduce(0, +) / Double(readings.count)
}()
}
var log = TemperatureLog(readings: [18, 20, 22])
print(log.average) // computing average, then 20.0
log.readings.append(40)
print(log.average) // still 20.0: a lazy value is never recomputed
let frozen = TemperatureLog(readings: [1, 2])
// print(frozen.average)
// error: cannot use mutating getter on immutable value: 'frozen' is a 'let' constantgo deeper
Recall that lazy delays a stored property's initial value until first use, and that it only works on var.
Explain why let cannot be lazy, why a lazy getter on a struct is mutating, and that the stored result is never recomputed when its inputs change.
Spot the production traps: stale lazy values used as caches, double initialization under concurrent first access, and copies of a struct each computing their own value.
Decide where deferred work belongs: per-instance lazy var for single-threaded cost savings, static let for shared exactly-once setup, explicit caching when values must follow inputs.
## What lazy changes A **lazy stored property** is a stored `var` marked with the `lazy` modifier. Its initial-value expression is not evaluated when the instance is created; it is evaluated the first time the property is read, and the result is stored in the instance like any other stored value. Later reads return the stored value without running the expression again. Two reasons to use it come straight from the language guide: - the initial value depends on something not known until initialization has finished, often other properties of `self`; - the initial value is expensive to build (a formatter, a parsed file, a large lookup table) and might never be needed. Because the expression runs after initialization, it may read `self`. A normal default value cannot: `var b = a + 1` fails with "cannot use instance member 'a' within property initializer; property initializers run before 'self' is available". A lazy property is often written as an immediately called closure, `lazy var x: T = { ... }()`, to hold several statements. ## Why var and never let A `let` constant must hold its value before initialization completes; that is what makes it constant. A lazy property gets its value later, at first access, which is a write after initialization. So `lazy let` is rejected with "'lazy' cannot be used on a let". `lazy` also cannot be applied to a computed property ("'lazy' cannot be used on a computed property"), since a computed property has no storage to fill. ## Lazy on a struct: a mutating getter On a structure, the first read of a lazy property writes into the instance. That makes its getter **mutating**, with consequences: 1. You cannot read it through a `let` constant: `let frozen = TemperatureLog(...)` followed by `frozen.average` fails with "cannot use mutating getter on immutable value: 'frozen' is a 'let' constant". 2. Copies taken before the first read each compute their own value. If `a` is copied to `b` and both are read, the initializer runs twice. 3. In a class, the instance is a reference, so a lazy property can be read through a `let` reference; the class's storage is written in place. ## A lazy value is not a cache The most common misunderstanding is that a lazy property tracks its inputs. It does not: - once computed, the value is **stale by design**: appending to `readings` after `average` has been read leaves `average` unchanged; - if you **assign** to the property before the first read, the initial-value expression never runs; - if you assign `nil` to an optional lazy property after it has been read, it stays `nil`; nothing recomputes it. If the value should follow its inputs, use a computed property (recomputed on every read) or store it and update it explicitly when the inputs change. Lazy properties may carry `willSet` and `didSet` observers; the first-access initialization does not call them, only later assignments do. ## Threads The language guide warns that if a lazy property is read from several threads at the same time before it has been initialized, there is no guarantee it will be initialized only once. In the Swift 6 language mode, data-race checking catches much of this at compile time: a class that conforms to `Sendable` cannot hold a lazy property ("stored property 'x' of 'Sendable'-conforming class 'C' is mutable"). A type marked `@unchecked Sendable` gets no such help, and the material on Sendable and data-race safety covers that escape hatch. When you need exactly-once initialization of shared state, use a stored type property, described below. ## Lazy compared with its neighbours | Declaration | When the value is produced | Recomputed? | Once under concurrent first access? | |---|---|---|---| | `lazy var` instance property | First read of that instance | Never | Not guaranteed | | Computed `var` | Every read | Every time | Not applicable | | `static let` / `static var` stored | First access to the type property | Never | Yes | | Plain stored `let` / `var` | During initialization | Never | Not applicable | Stored type properties are already lazy without the keyword, and the language guide guarantees they are initialized only once even under simultaneous access; writing `lazy` on a `static` property is an error ("'lazy' cannot be used on an already-lazy global"). A local variable is evaluated where it is declared unless you mark it `lazy`, which local variables also accept. The comparison shows when `lazy var` is the right tool: a per-instance value that is costly or depends on `self`, read from one thread or under the type's own synchronization, and not expected to change once built.
- Why may a lazy property's initial value refer to self when an ordinary default value cannot?Ordinary default values are evaluated while the instance is still being initialized, before self is available, so the compiler rejects them with "property initializers run before 'self' is available". A lazy initializer runs at the first read, which is always after initialization has finished, so self and its other properties are usable.
- How do you get a lazily created value that is initialized exactly once even when several threads read it first?Make it a stored static property: Swift initializes it lazily on first access and guarantees a single initialization even under simultaneous access. A per-instance lazy var gives no such guarantee, so per-instance shared state needs a lock or actor isolation around the first access.
- What happens if code assigns to a lazy property before anything has read it?The assigned value is stored and the initial-value expression never runs. The property is now an ordinary stored value; nothing later restores or recomputes the original expression.
- A lazy property is recomputed whenever the values it was built from change.
- Write lazy let to declare a constant computed on first use.
- Swift guarantees a lazy var is initialized only once across threads.
- Static stored properties need the lazy keyword to be initialized on first access.
- A lazy property of a struct can be read through a let constant.