Swift lazy stored property versus regular stored property when using closure

半城伤御伤魂 提交于 2019-12-01 08:50:54

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/33901342/swift-lazy-stored-property-versus-regular-stored-property-when-using-closure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!