sj9i8q
Last Updated: February 25, 2016
·
240
· citizen428
B3881a28fe402dd2d1de44717486cae8

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"
Say Thanks
Respond