Swift 2 Error Handling with asynchronous closures
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
// Error Handling // | |
enum Either<T> { | |
case Success(T) | |
case Failure(ErrorType) | |
func getValue() throws -> T { | |
switch self { | |
case .Success(let value): | |
return value | |
case .Failure(let error): | |
throw error | |
} | |
} | |
static func run(closure: () throws -> T) -> Either<T> { | |
do { | |
let result = try closure() | |
return .Success(result) | |
} catch { | |
return .Failure(error) | |
} | |
} | |
} | |
let r = Either.run { | |
return 12 | |
} | |
do { | |
let value = try r.getValue() | |
} catch { | |
print(error) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment