Created
July 7, 2018 01:32
-
-
Save Revolucent/72aded192f2e56d16f63255bb3c8c942 to your computer and use it in GitHub Desktop.
Throw if nil, otherwise return value
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
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