Search code examples
swiftlazy-evaluation

Lazy stored property in Swift


I am having some confusion in lazy stored property. I read many tutorials and found this, but I could not understand this in real scenario. Can anyone please clear out few things,

  1. A lazy stored property is a property whose initial value is not calculated until the first time it is used...

  2. You must always declare a lazy property as a variable (with the var keyword), because its initial value may not be retrieved until after instance initialization completes...

  3. Lazy properties are useful when the initial value for a property is dependent on outside factors whose values are not known until after an instance’s initialization is complete.

  4. Where should we use lazy stored property

Thanks


Solution

  • Mike Buss wrote an article about lazy initialization in Swift http://mikebuss.com/2014/06/22/lazy-initialization-swift/

    One example of when to use lazy initialization is when the initial value for a property is not known until after the object is initialized or when the computation of the property is computationally expensive.

    Here are two examples for both cases from the post:

    In the first example we don't know which value personalized greeting should have. We need to wait until the object is initialized to know the correct greeting for this person.

    class Person {
    
    var name: String
    
    lazy var personalizedGreeting: String = {
        [unowned self] in
        return "Hello, \(self.name)!"
        }()
    
    init(name: String) {
            self.name = name
        }
    }
    

    The second example covers the case of an expensive computation. Imagine a MathHelper class which should give you values for pi and other important constants. You don't need to calculate all constants if you only use a subset of them.

    class MathHelper {
    
    lazy var pi: Double = {
        // Calculate pi to a crazy number of digits
        return resultOfCalculation
        }()
    
    }