Last Updated: January 05, 2018
·
526
· citizen428

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"