Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ruddfawcett/83443786018fa78ef431dc9ed38e8a88 to your computer and use it in GitHub Desktop.
Save ruddfawcett/83443786018fa78ef431dc9ed38e8a88 to your computer and use it in GitHub Desktop.
cache a complicated computed property using the following pattern

Cached Properties

Complicated, time expensive computed properties can be cached using the following pattern.

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"
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!
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment