Skip to content

Instantly share code, notes, and snippets.

@Jeehut
Last active May 16, 2022
Embed
What would you like to do?
Convenience extensions to the Result type.
import Foundation
extension Result where Success == Void {
/// Convenience function to use in place of `.success(())` (gets rid of the `()` parameter).
public static func success() -> Self {
.success(())
}
}
extension Result {
/// Convenience access to the `.success` parameter if the ``Result`` is a success, else `nil`. If this is `nil`, ``unwrappedError`` is guaranteed to be not `nil`.
///
/// Thanks to this and ``unwrappedError``, instead of a switch like this:
/// ```
/// let value: SomeResponse
/// switch networkCall() {
/// case .success(let success):
/// value = success
///
/// case .failure(let error):
/// return .failure(error)
/// }
///
/// // some code using `value`
/// ```
///
/// You can write shorter code like that:
/// ```
/// let result = networkCall()
/// guard let value = result.successValue else { return .failure(result.unwrappedError) }
///
/// // some code using `value`
/// ```
public var successValue: Success? {
switch self {
case .success(let value):
return value
case .failure:
return nil
}
}
/// Convenience access to the `.failure` parameter if the ``Result`` is a failure. Calling this for a `.success` result will crash the app, so make sure to `guard` against it.
///
/// Thanks to this and ``successValue``, instead of a switch like this:
/// ```
/// let value: SomeResponse
/// switch networkCall() {
/// case .success(let success):
/// value = success
///
/// case .failure(let error):
/// return .failure(error)
/// }
///
/// // some code using `value`
/// ```
///
/// You can write shorter code like that:
/// ```
/// let result = networkCall()
/// guard let value = result.successValue else { return .failure(result.unwrappedError) }
///
/// // some code using `value`
/// ```
public var unwrappedError: Failure {
switch self {
case .failure(let error):
return error
case .success:
fatalError(
"""
Invalid call to `unwrappedError` for a `success` Result.
Wrap the call in a guard statement that checks for `.successValue` like so:
`guard let value = result.successValue else { throw result.unwrappedError }`
"""
)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment