What is the advantage or difference of initializing:
lazy var hintView: HintView = { let hintView = HintView() return hintView }()
Instead of simply use:
var hintView = HintView()
(HintView
is: class HintView: UIView {}
)
Help is very appreciated.
Swift has a mechanism built right into the language that enables just-in-time calculation of expensive work, and it is called a lazy variable. These variables are created using a function you specify only when that variable is first requested.
Another problem is that lazy var is not thread-safe which means the closure can get executed multiple times due to accesses from different threads.
The error message is completely useless at explaining what is going on, but essentially lazy and weak are at odds with each other: lazy tells Swift that you don't want your variable created until the first time you access it, but once it is created, you want to keep it indefinitely for future reference, while.
Important to note: You can use self inside the closure of a lazy property. It will not cause any retain cycles. The reason is that the immediately applied closure {}() is considered @noescape . It does not retain the captured self .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With