0Pricing
Swift Academy · Lesson

Lazy and Computed Properties

Lazy and Computed Properties

Introduction

Hello,

In the previous lesson, we learned about stored properties. You can also define lazy and computed properties.

What I saw in the previous section was to store the data (Store) of stored properties.

Apart from that, we can define properties as computed and lazy.

Lazy Properties

Lazy Properties

When a property value will not need to be generated until the first time the property value is used, you can use a lazy stored property.

When a property value is not used until its first use, we can use it as a lazy stored property. Therefore, if the production of an object is costly and it is not necessary for the first time, we will pass the production of the object at the first use of that object and avoid unnecessary resource consumption and performance loss. In order to make a stored property a lazy stored property, we need to pass the lazy modifier.

class Person {
    lazy var name: String = "Name"
    var age:Int = 0
    private var _lastName:String = ""
    func profile() -> String {
        return "I'm \(self.name) and I'm \(self.age) years old."
    }

}

var p = Person()

p.name = "Coddy"
p.age = 10

print(p.profile())
← Back to Swift Academy