Skip to content

Instantly share code, notes, and snippets.

@zadr
Last active Apr 26, 2017
Embed
What would you like to do?
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