Spaceship Operator in Swift

From Wikipedia:

Unlike traditional equality operators, which will return true or false depending on whether the arguments are equal or unequal, the spaceship operator will return 1, 0, or −1 depending on the value of the left argument relative to the right argument. If the left argument is greater than the right argument, the operator returns 1. If the left argument is less than the right argument, the operator returns −1. If the two arguments are equal, the operator returns 0.

Implementation in Swift is relatively straightforward:

operator infix <=> {}

@infix func <=><T: Comparable> (left: T, right: T) -> Int {
  if left < right { return -1 }
  if left > right { return  1 }
  return 0
}

Some results:

1 <=> 2   //Output: -1
2 <=> 1   //Output: 1
1 <=> 1   //Output: 0

2 thoughts on “Spaceship Operator in Swift

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s