Last active
January 2, 2020 10:27
-
-
Save vincent-pradeilles/8d0e981986cbc1ba09e16498ea45b077 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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