Created
July 11, 2015 08:08
-
-
Save JadenGeller/1be3c6bd82901899ece3 to your computer and use it in GitHub Desktop.
Memoized in Swift
This file contains hidden or 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
// 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