Search code examples
swiftcomputed-properties

Can I set computed property in get block in Swift?


var myProperty: PropertyType {
 get {
     if let alreadyComupted = savedValue {
       return alreadyComputed
     }
    return computeAndSave(someParam: "Hello")
 }
 set {
// is it possible to move *computeAndSave* body here somehow so I can call *set* method in above get definition?
 }
}

private var savedValue: PropertyType?
private func computeAndSave(someParam: SomeType) -> PropertyType {
// perform computations and assign value to *savedValue*
}

I am fairly new to swift language, not sure if this is even standard by coding practice or not.


Solution

  • Basically you are describing a lazy variable. It calculates its initializer once, when the value is first fetched, and from then on uses the stored value (unless it is replaced). You can combine this with a define-and-call initializer:

    lazy var myProperty: PropertyType = {
        let p = // perform some expensive one-time calculation here
        return p
    }()
    

    The outcome is that the first time you ask for the value of myProperty, the initializer method runs; but after that the previous result is used, and the initializer method never runs again.