Last active
August 29, 2015 14:13
-
-
Save wspringer/d1bda23faf61b599feca 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
import Cocoa | |
enum Try<T>: Printable, DebugPrintable { | |
// Captures a successful outcome | |
case Success(@autoclosure() -> T) | |
// Captures a failure, including the root cause, which for now can be anything | |
case Failure(Any) | |
func filter(fn: (T) -> Bool) -> Try<T> { | |
switch self { | |
case .Success(let value): | |
if fn(value()) { | |
return .Success(value) | |
} else { | |
return .Failure(NSError()) | |
} | |
default: return self | |
} | |
} | |
func map<U>(fn: (T) -> U) -> Try<U> { | |
switch self { | |
case .Success(let value): | |
return .Success(fn(value())) | |
case .Failure(let error): | |
return .Failure(error) | |
} | |
} | |
func flatMap<U>(fn: (T) -> Try<U>) -> Try<U> { | |
switch self { | |
case .Success(let value): | |
return fn(value()) | |
case .Failure(let error): | |
return .Failure(error) | |
} | |
} | |
func get() -> T { | |
switch self { | |
case .Success(let value): | |
return value() | |
case .Failure(let error): | |
assert(false, "Failed to extract successful value from failure") | |
} | |
} | |
func optional() -> T? { | |
switch self { | |
case .Success(let value): | |
return value() | |
case .Failure: | |
return nil | |
} | |
} | |
func isSuccess() -> Bool { | |
switch self { | |
case .Success: return true | |
case .Failure: return false | |
} | |
} | |
func isFailure() -> Bool { | |
return !isSuccess() | |
} | |
var description: String { | |
switch self { | |
case .Success(let value): | |
return "Success(\(value()))" | |
case .Failure(let error): | |
return "Failure" | |
} | |
} | |
var debugDescription: String { | |
return description | |
} | |
} | |
let s = Try.Success(5) | |
s.get() | |
let r = s.map({value in value * 19}) | |
r.get() | |
r.description | |
s.isFailure() | |
let t = s.filter({value in value < 2}) | |
t.optional() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment