Last active
April 26, 2017 21:36
-
-
Save zadr/f1d6a099b9662ec5c3f1643a982ab053 to your computer and use it in GitHub Desktop.
Ternary-ish operators without an else clause
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 ?? : 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() } | |
} |
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
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