Saturday, 13 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



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() {

    override func viewWillAppear(_ animated: Bool) {

    override func viewDidAppear(_ animated: Bool) {
         this is simple buildVerison property
         that get session after once initialize


For more info about lazy properties  watch below video

1 comment: