Created
January 30, 2021 11:09
-
-
Save swiftyfinch/4ef47a636a485fc4e1610ea06629d6b2 to your computer and use it in GitHub Desktop.
Unwrap nested Optionals or throw error.
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
protocol OptionalType { | |
associatedtype Wrapped | |
var optional: Wrapped? { get } | |
} | |
extension Optional: OptionalType { | |
var optional: Self { self } | |
} | |
extension Optional { | |
func unwrap(orThrow error: Error) throws -> Wrapped { | |
guard let unwrapped = self else { throw error } | |
return unwrapped | |
} | |
} | |
extension Optional where Wrapped: OptionalType { | |
func unwrap(orThrow error: Error) throws -> Wrapped.Wrapped { | |
guard let unwrapped = self as? Wrapped.Wrapped else { throw error } | |
return unwrapped | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment