Last active
May 31, 2016 10:47
-
-
Save joseprl89/236b84e731627109f414 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
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