Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Created July 11, 2015 08:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JadenGeller/1be3c6bd82901899ece3 to your computer and use it in GitHub Desktop.
Save JadenGeller/1be3c6bd82901899ece3 to your computer and use it in GitHub Desktop.
Memoized in Swift
// Inspired by and basically implemnted by http://intersections.tumblr.com/post/99634084704/unobservable-effects-with-value-types
// Cleaned up for Swift 2.0 (multi-load enums, yay!) and added value as mutating get instead of a mutating fuc
enum Memoized<T> {
case Evaluated(T)
case Unevaluated(() -> T)
var value: T {
mutating get {
switch self {
case .Evaluated(let x):
return x
case .Unevaluated(let f):
self = .Evaluated(f())
return value
}
}
}
}
// Example
var x = Memoized.Unevaluated { (1...10000000).reduce(0, combine: +) }
print("Thinking...")
for y in 1...3 {
print("I like the number \(x.value + y).")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment