Are Swift constants lazy by default?
Asked Answered
A

2

4

Something I still not quite understand about Swift ... let's say I want a property that instantiates a class in a base class used for several sub classes, e.g. ...

let horse = Horse();

Is horse instantiated right after app/class initialisation or when the property is accessed for the first time?

On the other hand using lazy var guarantees that the property is only instantiated the first time it is accessed ...

lazy var horse = Horse()

But then horse is not a constant. So in this case if I access horse multiple times I would get multiple instances of horse created, right?

What if I wanted both, a lazy property that is also a constant?

Apotheosize answered 13/6, 2015 at 5:34 Comment(0)
H
4

Not exactly. Say you have a class Farm and inside Farm there is horse property.

class Farm {
    let horse = Horse()
}

In this case horse property is initialized when class instance initialized. If you make it lazy you have to make it mutable too.

class Farm {
    lazy var horse = Horse()
}

In this case, horse property is initialized when it is accessed the first time. And later when it is accessed again it returns the same instance again instead of reinitializing it. But since it is a mutable property you can assign a new instance of Horse to it. After you assign it new value it will return this new value whenever it is accessed.

EDIT: If let horse = Horse() is defined in global space then it is lazily created at first access.

Hedva answered 13/6, 2015 at 6:7 Comment(1)
Thanks for clearing this up! So no way of creating a lazy constant. But good to know how it works.Apotheosize
L
0

Well, a bit late, but I think you can create a lazy property as constant using private(set) . Consider the example below :

import Foundation

struct GPS: CustomStringConvertible {
    let name: String

    init(name: String) {
        self.name = name
        print("GPS Initialised")
    }

    var description: String {
        return name
    }
}

struct Car {
    private(set) lazy var gps = GPS(name: "One")

    init() {
        print("Car Initialised")
    }
}

var someCar = Car()
print(someCar.gps) // Comment/Uncomment this to see lazy in action
//someCar.gps = GPS("Two") // This will create a compilation error
//

However, if you remove the private(set), it(gps variable inside Car) will become a variable again which can be mutated.

You can uncomment the last line after removing the private(set) to verify the same

Ledet answered 31/5, 2019 at 12:30 Comment(1)
well, it's not exactly a constant, it can still be modified inside the class itself ;)Posthumous

© 2022 - 2024 — McMap. All rights reserved.