Lazy store properties value not calculated until first accessed.
You can declare a lazy property with simply "lazy" keyword.
The closure associated to lazyproperty is executed only if you read the property. Lazy properties works with classor struct. Lazy store properties must be declare with var, because it's initial value might note be retrieved until after instance initialization complete.
Example :
class LazyExample{
var iCount = 0
func testFunc() -> String{
iCount += 1
return"iCount Value \(iCount)"
}
lazyvar tempLazy : String = {
print("access value")
returntestFunc()
}()
}
let lazyObj = LazyExample()
print(lazyObj.tempLazy) ///Only single time value access
print(lazyObj.tempLazy)
print(lazyObj.tempLazy)
Output:
access value
iCount Value 1
iCount Value 1
iCount Value 1
Another example :
class ViewController: UIViewController {
lazyvar buildVersion : String = {
print("only once initialize after that get from session")