[swift-evolution] Sort Descriptors

Chris Eidhof chris at eidhof.nl
Thu Nov 3 13:39:03 CDT 2016


Hey everyone,

I was wondering if there's any interest in adding Swift-like sort
descriptors to the language. Currently, we have `sort` and `sorted`, which
take a function of type `(A, A) -> Bool`. Foundation has
`NSSortDescriptor`, which corresponds more to `(A, A) -> ComparisonResult`.
NSSortDescriptor is a lot easier to work with than Swift's stdlib way: it's
more declarative, it's easy to combine multiple sort descriptors into one
(e.g. sort by last name, then sort by first name, and so on). However,
NSSortDescriptor uses runtime programming, and is not very typesafe.

We could do a lot better in Swift. There are at least a few possibilities:

typealias SortDescriptor<A> = (A, A) -> Bool
typealias SortDescriptor<A> = (A, A) -> ComparisonResult
struct SortDescriptor<A> { let compare: (A, A) -> Bool }
struct SortDescriptor<A> { let compare: (A, A) -> ComparisonResult }

I've experimented a bit with this, and it seems like the `struct` based
version with `ComparisonResult` is quite nice, because then we can add
methods/properties on it (e.g. to reverse a sort descriptor, or to return a
`Bool` instead of a `ComparisonResult`).

My "SortDescriptor" could also be called "Comparator", and in fact, there
is already something like that in Foundation (of type (Any,Any) -> Bool).

Is there interest in adding support for this to the stdlib? If yes, is
anyone interested in writing a good proposal together?

-- 
Chris Eidhof
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20161103/4daf0763/attachment.html>


More information about the swift-evolution mailing list