Skip to content

Instantly share code, notes, and snippets.

@orchetect
Last active October 20, 2021 02:38
Show Gist options
  • Save orchetect/83fb460d0d29f98f2e99f4d64b0d7938 to your computer and use it in GitHub Desktop.
Save orchetect/83fb460d0d29f98f2e99f4d64b0d7938 to your computer and use it in GitHub Desktop.
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