Fast lazy storage compared to regular stored property when using closure

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

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

vs

or make a closed closed closed property:

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

In both cases, the code used to get the value for the property runs only once. They seem to be equivalent.

When should a lazy stored property be used compared to a computed property when using closure with it?

+2
source share
1 answer
 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 in the properties, check the real time of their evaluation. lazy property is evaluated "on demand" when the first time a value is required

+14
source

Source: https://habr.com/ru/post/1012482/


All Articles