Skip to content

Instantly share code, notes, and snippets.

@pauljohanneskraft
Last active February 13, 2024 16:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pauljohanneskraft/bf20ae1a7d0c5c33a394fe66f858ff23 to your computer and use it in GitHub Desktop.
Save pauljohanneskraft/bf20ae1a7d0c5c33a394fe66f858ff23 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