Boon Boon - 3 months ago 15
Swift Question

lazy variable with closure

In this article, it says (referencing the code below): "You must use lazy to prevent the closure for being created more than once."

private lazy var variable:SomeClass = {
let fVariable = SomeClass()
fVariable.value = 10
return fVariable
}()


Why would lazy prevent the closure from being created more than once? And why would the lack of lazy cause it to evaluate more than once?

Answer

The tutorial code you quote is this:

private lazy var variable:SomeClass = {
    let fVariable = SomeClass()
    fVariable.value = 10
    return fVariable
}()

Contrast it with this:

private var variable:SomeClass {
    let fVariable = SomeClass()
    fVariable.value = 10
    return fVariable
}

The first one initializes variable to a newly created SomeClass instance, once at most (and maybe not even that many times). The second one is a read-only computed variable and creates a new SomeClass instance every time its value is read.

Comments