Add a Ruby-like "spaceship operator" to Swift
This provides a Ruby-like "spaceship operator" (<=>) for Swift. For more idiomatic Swift this uses an enum, however if you really want to, you can use the provided rawValue the same way you would in Ruby:
import Foundation
enum Compare: Int {
  case Right = -1, Equal, Left
}
infix operator <=> {}
func <=> <T: Comparable>(left: T, right: T) -> Compare {
  if left == right {
    return .Equal
  } else if left > right {
    return .Left
  } else {
    return .Right
  }
}
1 <=> 1             // .Equal
2.4 <=> 2.9         // .Right
"b" <=> "a"         // .Left
(0 <=> 1).rawValue  // -1
switch 0 <=> 1 {
case .Equal, .Left: print("That's odd")
default: print("All good")
}
// prints "All good"Written by Michael Kohl
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
 #Ruby 
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#

 
 
 
 
