Lazy variable with closure

This article says (referring to the code below): "You must use lazy to prevent closure to create more than once."

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

Why is lazy to prevent the creation of closure more than once? And why does the absence of the lazy make him evaluate more than once?

+4
source share
2 answers

The code for the textbook you are quoting is as follows:

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

Contrast this with this:

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

variable SomeClass, - (, , ). - SomeClass , .

+12

, . , / -. lazy , . lazy , .

, :

var myVar: MyType {
    return MyType()
}

:

var myVar: MyType = MyType()

, , :

lazy var myVar: MyType = MyType()

myVar - , myVar. , , myVar, .

myVar , , .

myVar - , ( , ) , .

:

lazy var myVar: MyType = { ... }()

:

func doStuffAndReturnMyType() { ... }
lazy var myVar: MyType = doStuffAndReturnMyType()

- , Swift ( ) () .

+10

Source: https://habr.com/ru/post/1611521/


All Articles