Swift - How and when to use Lazy lazy loading

As follows: the usage of the Lazy keyword in Swift, read carefully the effect of such keywords

//如下面的例子,不用Lazy修饰代码的执行顺序是从上到下的, 也就是说不管我用不用,它都创建,他都执行
let data = 1...3
let result = data.map {
    
     (i) -> Int in
    print("正在执行\(i)")
    return i * 2
}

print("准备访问结果")
for i in result{
    
    
    print("循环后的结果为\(i)")
}
print("操作完毕")

运行结果如下:
正在执行1
正在执行2
正在执行3
准备访问结果
循环后的结果为2
循环后的结果为4
循环后的结果为6
操作完毕
----------------------------------------------

//使用lazy修饰的话,不是按照谁的代码在上面而先执行的,而是你调用的时候发现需要上面的result这个时候才执行上面的代码来获取
let data = 1...3
let result = data.lazy.map {
    
     (i) -> Int in
    print("正在执行\(i)")
    return i * 2
}

print("准备访问结果")

for i in result {
    
    
    print("循环后的结果为\(i)")
}
print("操作完毕")

运行结果如下:
准备访问结果
正在执行1
循环后的结果为2
正在执行2
循环后的结果为4
正在执行3
循环后的结果为6
操作完毕
----------------------------------------------

It can be seen that this function, for example, if you create a button, the display of the button depends on the settings of the background, so you do not need to add the creation of this button to viewDidLoad, because it is created in viewDidLoad regardless of the settings of the background. All will be created, so if the background is set to not display, such a control will also be created, which virtually increases the code executed by viewDidLoad and consumes performance. You can write like this, define a lazy modified property XxButton separately, read the background settings in viewWillAppear, if it is set to display, write self.XxButton.isHidden = false in viewWillAppear, otherwise it will be reversed. ---- One sentence summary, lazy creates and executes the code when needed

Guess you like

Origin blog.csdn.net/SoftwareDoger/article/details/104423504