Friday, 12 October 2018

Lazy Properties

Lazy store properties value not calculated until first accessed.
You can declare a lazy property with simply "lazy" keyword.
The closure associated to lazy property is executed only if you read the property.
Lazy properties works with class or 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)"
    }
    lazy var tempLazy : String  = {
        print("access value")
        return testFunc()
    }()
}
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 {

    lazy var buildVersion : String = {
        print("only once initialize after that get from session")
        print("every time not get from app bundle")
        return (Bundle.main.infoDictionary?["CFBundleVersion"]  asString) ?? ""
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        print(buildVersion)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print(buildVersion)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        /*
         this is simple buildVerison property
         that get session after once initialize
         */
        print(buildVersion)
    }

}

For more info about lazy properties  watch below video