Skip to content

Instantly share code, notes, and snippets.

Created September 12, 2016 15:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/2c8df6186d5cb68005ac4d5397153748 to your computer and use it in GitHub Desktop.
Save anonymous/2c8df6186d5cb68005ac4d5397153748 to your computer and use it in GitHub Desktop.
ResultHandler
func identity<T>(value: T) -> T {
return value
}
enum Result<T, E> {
case Success(T)
case Error(E)
func map<R>(f: (T) -> R) -> Result<R, E> {
return mapResult(success: f, failure: identity)
}
func mapError<R>(f: (E) -> R) -> Result<T, R> {
return mapResult(success: identity, failure: f)
}
func mapResult<RT, RE>(success success: (T) -> RT, failure: (E) -> RE) -> Result<RT, RE> {
switch self {
case let .Success(value): return .Success(success(value))
case let .Error(error): return .Error(failure(error))
}
}
}
func executeThrowable<T, E: ErrorType>(closure: () throws -> T) -> Result<T, E?> {
do {
let result = try closure()
return .Success(result)
}
catch let error as E { return .Error(.Some(error)) }
catch { return .Error(.None) }
}
enum ConnectionFailure : ErrorType {
case Error
}
func throwConnectionError() throws -> String {
throw ConnectionFailure.Error
return connect()
}
func connect() -> String {
return "Connection"
}
executeThrowable(throwConnectionError)
.mapError { $0.map { (error: ConnectionFailure) -> () in
switch error {
case let .Error(value): print(value)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment