Sobes.tech
Junior

What is the purpose of the lazy keyword in Swift?

sobes.tech AI

Answer from AI

The lazy keyword is used for deferred initialization of a property. This means that the property's value is not computed when the instance of a structure or class is created, but only upon the first access to that property.

Advantages of using lazy:

  • Resource savings: Initialization can be an expensive operation (e.g., reading a file, network request), and if the property is not always used, deferred initialization can avoid unnecessary computations and memory costs.
  • Resolving cyclic dependencies: In some cases, property A may depend on property B, and property B — on property A. lazy can help break such dependencies.

Restrictions:

  • lazy properties must be mutable (var) because their value is set after the instance is created.
  • lazy properties cannot be constants (let).
  • Property observers (didSet, willSet) cannot be assigned to lazy properties.

Example of usage:

class DataFetcher {
    // Simulating an expensive operation
    func fetchData() -> [String] {
        print("Fetching data...")
        return ["Item 1", "Item 2", "Item 3"]
    }
}

class ViewController {
    let dataFetcher = DataFetcher()

    // Data will be loaded only upon first access to 'data'
    lazy var data: [String] = {
        self.dataFetcher.fetchData()
    }()

    func displayData() {
        print("Displaying data: \(data)")
    }

    func updateUI() {
        // Data is not used here, fetchData() is not called
        print("Updating UI...")
    }
}

let vc = ViewController()
// fetchData() has not been called at this point

vc.updateUI() // fetchData() still not called

vc.displayData() // fetchData() will be called here, upon first access to data
vc.displayData() // fetchData() will not be called again, cached value is used