Search code examples
swiftgetter-settercomputed-properties

Multiple Getters for Swift Properties?


Is there any way in Swift 3 to have a class with a computed property that is computationally expensive the first time, but remains constant afterwards, to have separate getters (an initial one, then another for each subsequent request)? i.e.

class Example {
    var computationallyIntensive: String? {
        return try? String(contentsOf: unlistedFile, encoding: .utf8)
    }
}

I am aware of initializers, however this property needn't be initialized at the creation of the class.

Ideally, the second call would return much sooner than the first:

let test = Example()
if test.computationallyIntensive == "base case" {
    print(test.computationallyIntensive)
}

Solution

  • Use a Lazy Stored Property:

    lazy var computationallyIntensive: String? = computeComputationallyIntensive()
    
    func computeComputationallyIntensive() -> String?  {
        return try? String(contentsOf: unlistedFile, encoding: .utf8)
    }
    

    The call to computeComputationallyIntensive, if any, will happen during the first call to computationallyIntensive.