What is the advantage of a lazy var in Swift
Lazy Stored Property vs Stored Property
There are a few advantages in having a lazy property instead of a stored property.
- The closure associated to the lazy property is executed only if you read that property. So if for some reason that property is not used (maybe because of some decision of the user) you avoid unnecessary allocation and computation.
- You can populate a lazy property with the value of a stored property.
- You can use
self
inside the closure of a lazy property
Let's do it practically. See the screenshot
I just stopped the debugger in viewDidLoad
. You can see that secondHintView
has a memory as it was not lazy for the storage but hintView
is still nil as it is a lazy one. The memory gets allocated once you use/access the lazy variables.
Also lazy should be var always.
A lazy stored property is calculated only when it is accessed for the first time.
It is var
and not let
because, the value is not initialized during the initialization process. It is calculated later on. That's why a lazy stored property need to be a variable
and not a constant
.
lazy var hintView: HintView = {
let hintView = HintView()
return hintView
}()
let h = hintView
In the above code, whenever, hintView
is accessed for the first time, the closure
assigned to it is executed and the value is returned and stored in h
.
For more info refer to:
Swift lazy stored property versus regular stored property when using closure
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html