Sort `Collection` using `KeyPath`

Going back to the point I was trying to make in my original reply, one way forward would be to separate this into a few proposals:

  • A proposal for some version of sort/sorted that takes (Self.Element) -> Comparable. This seems to be straightforwardly useful and uncontroversial, with mostly implementation details that still need to be discussed (e.g. should it be implemented using a Schwartzian transform or is the overhead not worthwhile for common use cases).
  • Ways to convert key paths, collections of key paths, etc. into closures (or types like SortDescriptor) that are useful for higher-order functions generally. For example, you might want convert a collection of key paths into an (Element) -> (T, U, …) closure to use in a map (and if tuples could conform to Comparable this would be directly usable for sorting, also). This is a large design space that will take time to explore and is inherently more controversial because it has implications for the long term design of the standard library.
  • Possibly separately, or part of the previous point, consider if there should be a bunch of convenience overloads (like the ones for sorted(by:) in @cal's picture above) for every higher order function to remove the need to use a prefix operator, or call/refer to an instance method, to convert from, say, a SortDescriptor into its underlying (T, T) -> Bool ordering function.

All these considerations are just as useful for things like partitioning, grouping elements of collections in a Dictionary by some derived key, etc, as @Ben_Cohen pointed out.

2 Likes