3 min readFeb 10, 2026
SwiftHow to Use Lazy Properties
Delay expensive setup until first use.
Steps
- Paste the code into a Swift file or playground.
- Run it once to verify the output.
- Adjust the inputs to match your use case.
Copy and paste
import Foundation
class DataStore {
lazy var cachedValue: String = {
return "Loaded" + String(Int.random(in: 1...100))
}()
}
let store = DataStore()
print(store.cachedValue)Notes
- Keep functions small and focused for reuse.
- Prefer safe APIs like optionals and guards.
