Last active
October 20, 2021 02:38
-
-
Save orchetect/83fb460d0d29f98f2e99f4d64b0d7938 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
extension Collection { | |
/** Elvis Operator (`?:` or `||` in other languages) | |
Works on String, Array, Collection, Set, etc. | |
Returns the left-hand value if it is not empty. | |
"" ?| "Default" // "Default" | |
"String" ?| "Default" // "String" | |
0 ?| 4 // 4 | |
1 ?| 4 // 1 | |
-1 ?| 4 // -1 | |
[] ?| [7,8] // [7,8] | |
[1,2] ?| [7,8] // [1,2] | |
*/ | |
public static func ?| (lhs: Self, rhs: @autoclosure () throws -> Self) rethrows -> Self { | |
!lhs.isEmpty ? lhs : try rhs() | |
} | |
} | |
extension BinaryInteger { | |
/// Elvis Operator (`?:` or `||` in other languages) | |
/// Returns the left-hand value if it is not 0. | |
public static func ?| (lhs: Self, rhs: @autoclosure () throws -> Self) rethrows -> Self { | |
lhs != 0 ? lhs : try rhs() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment