Swift Language Variables & Properties Lazy Stored Properties

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9


Lazy stored properties have values that are not calculated until first accessed. This is useful for memory saving when the variable's calculation is computationally expensive. You declare a lazy property with lazy:

lazy var veryExpensiveVariable = expensiveMethod()

Often it is assigned to a return value of a closure:

lazy var veryExpensiveString = { () -> String in
    var str = expensiveStrFetch()
    str.expensiveManipulation(integer: arc4random_uniform(5))
    return str

Lazy stored properties must be declared with var.

Got any Swift Language Question?