[swift-evolution] [Idea] Switching Comparable types: a new operator

Dave Abrahams dabrahams at apple.com
Thu Feb 4 18:10:02 CST 2016


on Thu Feb 04 2016, Jonathan Tang <swift-evolution at swift.org> wrote:

> Can't you define this yourself?  This worked in a Playground using Swift
> 2.1:
>
> enum Ordering {
>     case OrderedSame, OrderedAscending, OrderedDescending
> }
>
> infix operator <=> {}
> func <=> <T: Comparable>(x: T, y: T) -> Ordering {
>     if x < y {
>         return .OrderedAscending
>     } else if x > y {
>         return .OrderedDescending
>     } else {
>         return .OrderedSame
>     }
> }
>
> let x = 3
> let y = 4
> switch x <=> y {
> case .OrderedSame:
>     print(3)
> case .OrderedAscending:
>     print(4)  // Executed
> case .OrderedDescending:
>     print(5)
> }

The problem is that the stdlib algorithms don't use this, so sorting,
e.g., an array of arrays of strings ends up being more expensive than
necessary.  What you really want is for the "spaceship operator" to be
the primary implementation hook that gets called from the comparison
predicates.

It's on the agenda for swift 3 to add the spaceship operator, and make
the algorithms use it, and solve the migration problems for old code,
and solve the interop problems with foundation.  However, we have a lot
of other work on our hands, and there's always a chance we won't fit it
in the schedule.  This could make a great after-starter project for
someone out there who wanted to take it on (hint, hint).

-- 
-Dave



More information about the swift-evolution mailing list