Skip to content

Instantly share code, notes, and snippets.

@zadr
Last active April 26, 2017 21:36
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 zadr/f1d6a099b9662ec5c3f1643a982ab053 to your computer and use it in GitHub Desktop.
Save zadr/f1d6a099b9662ec5c3f1643a982ab053 to your computer and use it in GitHub Desktop.
Ternary-ish operators without an else clause
infix operator ?? : Branching
precedencegroup Branching {
associativity: left
lowerThan: ComparisonPrecedence // also accounts for NilCoalescingPrecedence
}
/// Ternary-y operators without an else clause
///
/// - Parameter lhs: The Boolean value to evaluate
/// - Parameter rhs: A closure to run if the lhs evaluates to true
public func ?? (lhs: Bool, rhs: @autoclosure () -> Void) {
if lhs { rhs() }
}
true ?? print("hi") // prints "hi"
2 + 2 == 5 ?? print("lol") // doesn't laugh
func blorp(_ x: Operation?) {
x?.cancel()
x?.isCancelled ?? false ?? gogogo(x!)
}
func gogogo(_ x: Operation) {
x.main()
}
blorp(BlockOperation(block: { print("1a2a3a") })) // prints 1a2a3a
blorp(nil) // does nothing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment