Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Last active August 29, 2015 14:17
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 JadenGeller/2e26cfd58fabedefa204 to your computer and use it in GitHub Desktop.
Save JadenGeller/2e26cfd58fabedefa204 to your computer and use it in GitHub Desktop.
Swift Combined Comparison Operator
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