Last active
August 29, 2015 14:17
-
-
Save JadenGeller/2e26cfd58fabedefa204 to your computer and use it in GitHub Desktop.
Swift Combined Comparison Operator
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 <=> { associativity none precedence 130 } | |
func <=><T: Comparable>(lhs: T, rhs: T) -> NSComparisonResult { | |
if lhs > rhs { | |
return .OrderedDescending | |
} | |
else if lhs < rhs { | |
return .OrderedAscending | |
} | |
else { | |
return .OrderedSame | |
} | |
} | |
// Super simple example | |
func isAffordable(cost: Int, money: Int) { | |
switch cost <=> money { | |
case .OrderedAscending: println("We can buy it with $\(money-cost) left over!") | |
case .OrderedSame: println("We have just enough.") | |
case .OrderedDescending: println("Insufficient funds :O") | |
} | |
} | |
isAffordable(5, 9) // -> "We can buy it with $4 left over!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment