Sobes.tech
Junior — Middle

What are the differences between properties that are implemented lazily and those that are computed on the fly?

sobes.tech AI

Answer from AI

Lazy properties and computed properties differ in the way and timing of value initialization:

  • Lazy properties are initialized only upon the first access. The value is stored and returned for subsequent accesses. This is convenient if initialization is resource-intensive and not always needed.

  • Computed properties do not store a value but compute it anew each time they are accessed. They are usually implemented via getters (and setters) and do not occupy additional memory for storage.

Example in Swift:

class Example {
    lazy var lazyValue: String = {
        print("Initializing lazy property")
        return "Lazy value"
    }()

    var computedValue: String {
        print("Computing property")
        return "Computed value"
    }
}

let example = Example()
// lazyValue is not yet initialized
print(example.lazyValue) // Initializing lazy property
                        // Lazy value
print(example.lazyValue) // Lazy value (without re-initialization)

print(example.computedValue) // Computing property
                             // Computed value
print(example.computedValue) // Computing property
                             // Computed value

Thus, the lazy property stores the result after the first computation, while the computed property recalculates on each access.

What are the differences between properties that are… - sobes.tech