Created
September 12, 2016 15:39
-
-
Save anonymous/7d3f49b28c4260a19fe5eeb9f97d681f to your computer and use it in GitHub Desktop.
ResultHandler
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
func identity<T>(value: T) -> T { | |
return value | |
} | |
func transform<T, E>(value: T) -> E? { | |
return value as? E | |
} | |
func mapTransform<T, E, R>(value: T, closure: (value: E) -> R) -> R? { | |
return transform(value).map(closure) | |
} | |
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>(closure: () throws -> T) -> Result<T, ErrorType> { | |
do { | |
let result = try closure() | |
return .Success(result) | |
} | |
catch let error { return .Error(error) } | |
} | |
enum ConnectionFailure : ErrorType { | |
case Error | |
} | |
func throwConnectionError() throws -> String { | |
throw ConnectionFailure.Error | |
return connect() | |
} | |
func connect() -> String { | |
return "Connection" | |
} | |
executeThrowable(throwConnectionError) | |
.mapError { error in | |
mapTransform(error) { (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