Swift Resources & Notes

February 8th, 2020

Caching computed properties

Swift has computed properties; here's a pattern for caching them: https://gist.github.com/pauljohanneskraft/bf20ae1a7d0c5c33a394fe66f858ff23

struct Cached <T, U> {
    var value : T { willSet { _calculated = nil } }
    private var _calculated : U? = nil
    private var function : (T) -> U
    
    init(_ value: T, _ f: (T) -> U) {
        self.function = f
        self.value = value
    }
    
    var calculated : U {
        mutating get {
            if _calculated == nil { _calculated = function(value) }
            return _calculated!
        }
    }
}

Example use:

var a = Cached(0) {
    (a: Int) -> Int in
    print("did calculate")
    return a + 100
}
// Prints "did calculate"

print(a.calculated)
// Prints "100"

a.value = 10

print(a.calculated)
// Prints "did calculate\n110"

Nice tips on use language features to make more expressive, explicit code

https://www.swiftbysundell.com/articles/what-makes-code-swifty/ via https://news.ycombinator.com/item?id=22399082