Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 712
Boon Avatar asked Oct 14 '15 00:10

Boon


1 Answers

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.

like image 181
matt Avatar answered Nov 25 '22 09:11

matt