Skip to content

Instantly share code, notes, and snippets.

@Revolucent
Created July 7, 2018 01:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Revolucent/72aded192f2e56d16f63255bb3c8c942 to your computer and use it in GitHub Desktop.
Save Revolucent/72aded192f2e56d16f63255bb3c8c942 to your computer and use it in GitHub Desktop.
Throw if nil, otherwise return value
infix operator ??!: NilCoalescingPrecedence
/**
If the left-hand side in nil, the error on the right-hand side is thrown. Otherwise,
the unwrapped value is returned. For example:
```
// Instead of this…
guard let x = y else {
throw SomeError.someError
}
// You can say this…
let x = try y ??! SomeError.someError
```
*/
@discardableResult func ??!<T>(lhs: T?, rhs: @autoclosure () -> Error) throws -> T {
guard let lhs = lhs else {
throw rhs()
}
return lhs
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment