Skip to content

Instantly share code, notes, and snippets.

@joseprl89
Last active May 31, 2016 10:47
Show Gist options
  • Save joseprl89/236b84e731627109f414 to your computer and use it in GitHub Desktop.
Save joseprl89/236b84e731627109f414 to your computer and use it in GitHub Desktop.
enum MyError: ErrorType {
case Test
}
enum Future<WrappedObject> {
case Present(value:WrappedObject)
case Error(error:ErrorType)
case Finally
case None
}
extension Future {
func then<NewWrappedType>(block: (WrappedObject) throws -> NewWrappedType) -> Future<NewWrappedType> {
switch self {
case let .Present(wrapped):
do {
// On success, return a present
return try .Present(value: block(wrapped))
}
catch let error {
// On error an error
return .Error(error:error)
}
// In other case, throw the current status down the line.
case let .Error(error):
return .Error(error:error)
case .Finally:
return .Finally
case .None:
return .None
}
}
func onError(block: (error:ErrorType) -> ()) -> Future {
switch self {
case let .Present(wrapped):
return .Present(value: wrapped)
case let .Error(error):
block(error: error)
fallthrough
case .Finally:
return .Finally
case .None:
return .None
}
}
func finally(block: () -> ()) {
block()
}
}
// Start with an int
let future = Future.Present(value: 1)
// Convert to string
future.then { (input) in
return "\(input)"
}
// Print it
.then { (stringInput) in
let s = stringInput
print(s)
}
// Throw an exception
.then {
throw MyError.Test
}
// Catch it
.onError { (error) -> () in
let error = "Error! \(error)"
print(error)
}
.finally { () -> () in
let msg = "Always runs"
print(msg)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment