[Swift] About lazy

Swift

Introduction

I didn't know what lazy affects and what lazy is. An official document says

A lazy stored property is a property whose initial value is not calculated until the first time it is used

It means if the variable which has lazy attribute it is not calculated when it is been used at first.

This is an example oflazy.

import Foundation

struct SmartPhone {
    let os: String
    let version: Int
}

struct SmartPhoneHandler {

    let smartPhone: SmartPhone

    init(smartPhone: SmartPhone) {
        self.smartPhone = smartPhone
        print("Initializer called")
    }

    lazy var company: String = {
        print("Lazy property called")
        if (smartPhone.os == "iOS"){
           return "Apple"
        } else if (smartPhone.os == "Android") {
           return  "Google"
        } else {
            return "Another"
        }
    }()
}

var smartPhoneHandler = SmartPhoneHandler(smartPhone: SmartPhone(os: "Android", version: 14))
let company = smartPhoneHandler.company

// Initializer called
// Lazy property called

You can see that after initializer is called lazy property is defined.

Comparison of Lazy stored property and Computed property

They have some similar features.

  • How to define
  • lazy assesment

But the big difference is How many times are the variables calculated?

Let's return to the example of smart phone. You can see

The below is lazy stored property.

    lazy var company: String = {
        print("Lazy property called")
        if (smartPhone.os == "iOS"){
           return "Apple"
        } else if (smartPhone.os == "Android") {
           return  "Google"
        } else {
            return "Another"
        }
    }()

On the other hand, the below is computed property.

    var company: String {
        print("Lazy property called")
        if (smartPhone.os == "iOS"){
           return "Apple"
        } else if (smartPhone.os == "Android") {
           return  "Google"
        } else {
            return "Another"
        }
    }()

lazy stored perperty is calculated at once when being called at first. But computed perperty is calculated every time when being called.

Thank you.

References
Big helpful article.

コメント

タイトルとURLをコピーしました