Last active
February 6, 2017 10:21
-
-
Save Oyvindkg/30f06a10a5ffa27dcb6664d7b9db6847 to your computer and use it in GitHub Desktop.
Swift 3: An enum used for error handling in asynchronous calls
This file contains hidden or 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
/** | |
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