Lazy Loading Implementation in Swift
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Lazy Loading runs in O(1) time and O(1) space, in Swift as in every other language.
- ✓Laziness here is grammar, not library. lazy var on a stored property defers its initialiser to the first read.
- ✓Single ownership is the rule reviewers apply to lazy var, and they apply it out loud. Anything reachable from more than one task moves behind an actor or a lock instead, since the keyword supplies no synchronisation and emits no warning about it.
- ✓The Swift trap: lazy var on a struct compiles to a mutating getter, because reading it writes the backing storage.
- ✓The resting cost is real and easy to overlook. Storage the compiler synthesises alongside a lazy property is an Optional<T>, so a type with three lazy fields grows by three tag-and-payload slots before a single one of them is built.
What Lazy Loading actually is
Lazy Loading in Swift: what you actually reach for
Swift implementation
import Foundation
// Globals and statics are lazy in Swift whether you ask for it or not: the
// compiler routes the first access through swift_once, so this table is
// built on first touch, exactly once, with no lazy keyword anywhere.
let opcodeTable: [String: UInt8] = [
"nop": 0x00, "push": 0x10, "add": 0x20, "jmp": 0x30,
]
enum Trace {
// Non-Sendable shared state is rejected in Swift 6 language mode even
// though swift_once would initialise it correctly. Built exactly once
// is not the same claim as safe to touch from two tasks.
@MainActor static let stamp = ISO8601DateFormatter()
}
final class Disassembler {
private let bytes: [UInt8]
// A lazy var compiles to an unsynchronised optional-check getter, and
// in a struct it would be a *mutating* getter. It is a convenience for
// single-task ownership, never a once-token.
lazy var mnemonics: [String] = bytes.map { byte in
opcodeTable.first { $0.value == byte }?.key ?? "??"
}
init(bytes: [UInt8]) { self.bytes = bytes }
}
// The concurrency-safe per-instance form: the actor serialises the build.
actor SymbolCache {
private var symbols: [String]?
func resolve() -> [String] {
if let symbols { return symbols }
let built = opcodeTable.keys.sorted()
symbols = built
return built
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Swift-specific trap
Performance in Swift, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Swift type or library should I use for Lazy Loading?
Laziness here is grammar, not library. lazy var on a stored property defers its initialiser to the first read. More significantly, every global and every static member is already lazy whether you asked or not: the compiler routes the first access through swift_once, so static let shared = ... is a correctly synchronised singleton with no dispatch_once boilerplate and no double-checked locking written anywhere. When the deferred value has to be shared across tasks, the tools are actor for serialised access, @MainActor for main-thread isolation, and nonisolated(unsafe) as the explicit escape hatch.
What is the most common Swift mistake when implementing Lazy Loading?
lazy var on a struct compiles to a mutating getter, because reading it writes the backing storage. That one fact produces two surprises no other language on this page has. Reading the property through a let binding is a compile error, not a runtime one: cannot use mutating getter on immutable value. And since structs copy by value, every copy carries its own uninitialised slot and re-runs the initialiser independently, so a cached table gets rebuilt once per copy. Swift 6 language mode adds a third: static let of a non-Sendable type is rejected outright, because initialising once says nothing about sharing safely.
How does Lazy Loading actually perform in Swift?
The resting cost is real and easy to overlook. Storage the compiler synthesises alongside a lazy property is an Optional<T>, so a type with three lazy fields grows by three tag-and-payload slots before a single one of them is built. The global and static path behaves differently: after the first call swift_once is a load of the once token and a branch, cheap enough that hoisting a global into a local buys nothing measurable. A protocol-typed lazy property stores an existential container, which heap-allocates whenever the value does not fit the inline buffer, and that is the allocation people miss when profiling. Time complexity is O(1) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what GitHub Copilot offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.