Created
June 11, 2023 21:41
-
-
Save adam-zethraeus/73ddd4f075fd1bb95175b024a0bba000 to your computer and use it in GitHub Desktop.
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
extension Optional { | |
func orThrow(_ error: (any Error)? = nil) throws -> Wrapped { | |
switch self { | |
case .none: | |
if let error { | |
throw error | |
} else { | |
throw OptionalUnwrappingError(Wrapped.self) | |
} | |
case .some(let wrapped): | |
return wrapped | |
} | |
} | |
func unwrappingResult() -> Result<Wrapped, OptionalUnwrappingError<Wrapped>> { | |
switch self { | |
case .none: | |
return .failure(OptionalUnwrappingError(Wrapped.self)) | |
case .some(let wrapped): | |
return .success(wrapped) | |
} | |
} | |
} | |
// MARK: - OptionalUnwrappingError | |
public struct OptionalUnwrappingError<T>: Error { | |
public init(_: T.Type) { } | |
public let description = "Could not unwrap \(T.self)?" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment