Skip to content

Instantly share code, notes, and snippets.

@vincent-pradeilles
Last active January 2, 2020 10:27
Show Gist options
  • Save vincent-pradeilles/8d0e981986cbc1ba09e16498ea45b077 to your computer and use it in GitHub Desktop.
Save vincent-pradeilles/8d0e981986cbc1ba09e16498ea45b077 to your computer and use it in GitHub Desktop.
@propertyWrapper
struct Cached<Input: Hashable, Output> {
private var cachedFunction: (Input) -> Output
init(wrappedValue: @escaping (Input) -> Output) {
self.cachedFunction = Cached.addCachingLogic(to: wrappedValue)
}
var wrappedValue: (Input) -> Output {
get { return self.cachedFunction }
set { self.cachedFunction = Cached.addCachingLogic(to: newValue) }
}
private static func addCachingLogic(to function: @escaping (Input) -> Output) -> (Input) -> Output {
var cache: [Input: Output] = [:]
return { input in
if let cachedOutput = cache[input] {
return cachedOutput
} else {
let output = function(input)
cache[input] = output
return output
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment