使用闭包时的Swift惰性存储属性与常规存储属性 [英] Swift lazy stored property versus regular stored property when using closure

查看:92
本文介绍了使用闭包时的Swift惰性存储属性与常规存储属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift中,我们可以将存储的属性设置为使用闭包:

In Swift, we can set a stored property to use closure:

class Test {
  var prop: String = {
    return "test"
  }()
}

vs

或使惰性存储属性使用闭包:

or make lazy stored property use closure:

class Test {
  lazy var prop: String = {
    return "test"
  }()
}

在两种情况下,用于获取属性值的代码仅运行一次.似乎它们是等效的.

In both cases, the code used to obtain the value for the property is only run once. It seems like they are equivalent.

与闭包一起使用时,什么时候应该使用惰性存储属性而不是计算属性?

When should I use lazy stored property versus computed property when using closure with it?

推荐答案

import Foundation
struct S {
    var date1: NSDate = {
        return NSDate()
    }()
    lazy var date2: NSDate = {
        return NSDate()
    }()
}

var s = S()
sleep(5)
print( s.date2, s.date1)
/* prints

2015-11-24 19:14:27 +0000 2015-11-24 19:14:22 +0000

*/

都是存储的属性,请检查它们的实时评估时间.第一次需要该值时,将对惰性属性进行按需"评估

both are stored properties, check the real time at which they are evaluated. the lazy property is evaluated 'on demand' when first time the value is needed

这篇关于使用闭包时的Swift惰性存储属性与常规存储属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆