Skip to content

Instantly share code, notes, and snippets.

@Oyvindkg
Last active February 6, 2017 10:21
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 Oyvindkg/30f06a10a5ffa27dcb6664d7b9db6847 to your computer and use it in GitHub Desktop.
Save Oyvindkg/30f06a10a5ffa27dcb6664d7b9db6847 to your computer and use it in GitHub Desktop.
Swift 3: An enum used for error handling in asynchronous calls
/**
Represents the result of an asynchronous call.
Can be either a successfull result containing a return value, or a failure containing an error.
*/
public enum Result<Value> {
case failure(error: Error)
case success(value: Value)
/** The value, if successful */
var value: Value? {
switch self {
case .success(let value):
return value
case .failure:
return nil
}
}
/** The error, if unsuccessful */
public var error: Error? {
switch self {
case .success:
return nil
case .failure(let error):
return error
}
}
/**
Transform the result value, or propagate any errors gracefully.
This can be used to transform the result without having to verify its content. Any thrown errors will be propagated
- parameters:
- transform: the closure used to transform the original value
- returns: a result with the transformed value, or the original error
*/
public func transform<NewValue>(with transformer: (Value) throws -> NewValue) -> Result<NewValue> {
switch self {
case .success(let value):
do {
let transformedValue = try transformer(value)
return .success(value: transformedValue)
}
catch(let error) {
return .failure(error: error)
}
case .failure(let error):
return .failure(error: error)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment