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, not let
  • Not thread-safe by default — use care in concurrent contexts
  • Great for views, formatters, and other setup-heavy properties

Rate your understanding:

Ready to practice more Swift?

Test yourself with our interactive quiz mode or browse all curated questions for this topic.