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 {} )
HintView
class HintView: UIView {}
Help is greatly appreciated.
There are several advantages of a lazy property over a stored property.
self
Do it practically. See screenshot
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.
viewDidLoad
secondHintView
hintView
Also lazy should always be var.
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 .
var
let
variable
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 .
closure
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
In some cases, using lazy vars can be faster because they are only calculated once when you first access them.
lazy
Source: https://habr.com/ru/post/1012481/More articles:Publishing with Visual Studio 2017 MVC ASP.NET Core "They Must Have the Same Number of Elements" - asp.net-core-mvcFileStream / StreamWriter in .NET Core 1.1 does not have a Close () method - c #constructor does not introduce a C # function - functionElisp: how can I express else-if - lispHow to find out what works in a Jupyter laptop? - pythonFast lazy storage compared to regular stored property when using closure - closuresEF Core Scaffold DbContext - .netAndroid Studio: breakpoint in static interface method not working - java"unsafely-treat-insecure-origin-as-secure" flag does not work in Chrome - google-chromeSQLAlchemy (ORM) versus raw SQL queries - pythonAll Articles