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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With