Created
January 31, 2020 21:59
-
-
Save embassem/e848ef057cb3173e7db8ec8a15f8833f to your computer and use it in GitHub Desktop.
add extension for result Type to access value and error
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
extension Result { | |
var value: Success? { | |
guard case .success(let value) = self else { return nil } | |
return value | |
} | |
/// Returns the associated error value if the result is a failure, `nil` otherwise. | |
var error: Failure? { | |
guard case .failure(let error) = self else { return nil } | |
return error | |
} | |
/// let possibleData: Result<Data> = .success(Data(...)) | |
/// let possibleObject = possibleData.flatMap { | |
/// try JSONSerialization.jsonObject(with: $0) | |
/// } | |
/// | |
/// - parameter transform: A closure that takes the success value of the instance. | |
/// | |
/// - returns: An `AFResult` containing the result of the given closure. If this instance is a failure, returns the | |
/// same failure. | |
func flatMap<T>(_ transform: (Success) throws -> T) -> Result<T,Error> { | |
switch self { | |
case .success(let value): | |
do { | |
return try .success(transform(value)) | |
} catch { | |
return .failure(error) | |
} | |
case .failure(let error): | |
return .failure(error) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment