SwiftMidMCQ
What is `lazy` property and when is it useful?
Test your knowledge:
Explanation & Code
Answer:
A lazy property is only computed the first time it is accessed. Useful for expensive operations you may not always need.
Code Example:
class DataProcessor {
// Only created when first accessed
lazy var expensiveData: [String] = {
print("Computing...")
return loadFromDisk() // expensive operation
}()
}
let processor = DataProcessor()
// expensiveData not computed yet
let data = processor.expensiveData // computed now, cached after
let again = processor.expensiveData // returned from cache, no recompute
Key Points:
- Must be
var, notlet - Not thread-safe by default — use care in concurrent contexts
- Great for views, formatters, and other setup-heavy properties
Rate your understanding: