Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the advantage of a lazy var in Swift

Tags:

swift

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.

like image 405
David Seek Avatar asked Nov 19 '16 15:11

David Seek


People also ask

What is lazy in IOS Swift?

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.

Is lazy var thread safe Swift?

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.

What is lazy and weak in Swift?

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.

Can we capture a lazy variable inside a closure or not?

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 .


1 Answers

Let's do it practically. See the screenshot

enter image description here

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.

like image 157
Rajan Maheshwari Avatar answered Oct 08 '22 05:10

Rajan Maheshwari