Reputation: 27
Today I saw some code which confused me:
lazy var variable = {......}()
I hope someone can explain for me the usage of lazy
.
Upvotes: 0
Views: 144
Reputation: 21137
lazy var variable: Class = {
<initialisation>
return <resulting object>
}()
is equivalent to:
var _variable: Class?
var variable: Class {
get{
if _variable == nil {
<initialisation>
_variable = <resulting object>
}
return _variable!
}
}
In short: it initialises the object when it is needed
Upvotes: 0
Reputation: 1285
In the example code posted in your question, the lazy qualifier causes the instance variable to be initialized to the assignment once and only when and if the variable is referenced. In this example, the assignment is actually the result of a closure evaluation which could possibly be expensive. Marking the variable as lazy reduces the overhead when instantiating the object by deferring the evaluation of the closure until the variable is actually used. Furthermore, the assignment may have dependencies that would not be satisfied during the normal phase of initialization of the variable, but would be satisfied during the first access of the variable. Hence, the lazy initialization may allow for the variable to be initialized at a more appropriate time.
Upvotes: 0
Reputation: 1878
Lazy initialization (also sometimes called lazy instantiation, or lazy loading) is a technique for delaying the creation of an object or some other expensive process until it’s needed. When programming for iOS, this is helpful to make sure you utilize only the memory you need when you need it.
This technique is so helpful, in fact, that Swift added direct support for it with the lazy attribute.
To understand why this is useful, let's first go over the old way of creating lazy properties.
Have a look at this link
Upvotes: 1