Skip to content

Instantly share code, notes, and snippets.

@swiftyfinch
Created January 30, 2021 11:09
Show Gist options
  • Save swiftyfinch/4ef47a636a485fc4e1610ea06629d6b2 to your computer and use it in GitHub Desktop.
Save swiftyfinch/4ef47a636a485fc4e1610ea06629d6b2 to your computer and use it in GitHub Desktop.
Unwrap nested Optionals or throw error.
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