Skip to content

Instantly share code, notes, and snippets.

@jtodaone
Last active July 24, 2023 19:41
Show Gist options
  • Save jtodaone/68e08ab2a000fee340884ac443040b1e to your computer and use it in GitHub Desktop.
Save jtodaone/68e08ab2a000fee340884ac443040b1e to your computer and use it in GitHub Desktop.
This piece of code introduces ..? operator which lets you handle unexpected nil found in an optional just like you would with any other Swift errors - with do/try/catch.
postfix operator ..?
extension Optional {
static postfix func ..? (optional: Optional<Wrapped>) throws -> Wrapped {
if let value = optional {
return value
} else {
throw OptionalUnwrapError.nilFound
}
}
}
enum OptionalUnwrapError: Error {
case nilFound
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment