What is the advantage of lazy var in Swift

What is the advantage or difference of initialization:

lazy var hintView: HintView = { let hintView = HintView() return hintView }() 

Instead of simple use:

 var hintView = HintView() 

( HintView : class HintView: UIView {} )

Help is greatly appreciated.

+6
source share
4 answers

Lazy Stored Property vs Saved Property

There are several advantages of a lazy property over a stored property.

  • A closure associated with a lazy property only occurs if you are reading this property. Therefore, if for some reason this property is not used (perhaps due to some decision by the user), you avoid unnecessary selection and calculation.
  • You can populate a lazy property with the value of the stored property.
  • You can use self in closing a lazy property
+12
source

Do it practically. See screenshot

enter image description here

I just stopped the debugger in viewDidLoad . You can see that secondHintView has memory since it was not lazy for storage, but hintView is still nil as it is lazy > one. Memory is allocated after use / access to lazy variables.

Also lazy should always be var.

+21
source

A lazy stored property is calculated only the first time it is accessed.

This is var , not let , because this value is not initialized during the initialization process. It is calculated later. Therefore, for a lazy stored property, there must be variable , not constant .

 lazy var hintView: HintView = { let hintView = HintView() return hintView }() let h = hintView 

In the above code, each time the hintView is hintView , the closure assigned to hintView is executed, and the value is returned and stored in h .

For more information, refer to:

Fast lazy stored property versus regular stored property when using closure

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html

+2
source

In some cases, using lazy vars can be faster because they are only calculated once when you first access them.

0
source

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


All Articles