What is the significance of 'lazy' properties in Swift, and how do you use them?
Instruction: Explain the concept of 'lazy' properties and provide a practical example of their use.
Updated
Official answer
A lazy stored property computes its initial value when first accessed. It must be a var because initialization can occur after the containing instance is initialized. This can avoid unused work, but it moves any required work to first access; it does not run the initializer asynchronously or guarantee a faster first interaction.
This complete sequential example makes the one-time work visible:
final class Catalogue {
private(set) var builds = 0
lazy var labels: [String] = {
builds += 1
return (1...3).map { "Item \($0)" }
}()
}
let catalogue = Catalogue()
assert(catalogue.builds == 0)
assert(catalogue.labels == ["Item 1", "Item 2", "Item 3"])
assert(catalogue.builds == 1)
_ = catalogue.labels
assert(catalogue.builds == 1)
catalogue.labels = ["Replacement"]
assert(catalogue.labels == ["Replacement"] && catalogue.builds == 1)
The stored value is reused until explicitly replaced; changing other inputs does not automatically invalidate it. If the value must follow changing state, use a computed property or an explicit cache with an invalidation policy.
An instance lazy property is not guaranteed to initialize only once when multiple threads first access it simultaneously. Isolate the instance or synchronize access. This differs from Swift's once-only stored type-property initialization. Also remember that accessing a lazy property on a struct can require mutable access.
Use lazy for appropriately bounded local construction, not synchronous remote fetching on the main thread. Measure both initialization and first-use latency, memory retention and invalidation behavior before claiming a benefit.