问题
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