[swift-evolution] [Discussion] Sortable Attribute

Xiaodi Wu xiaodi.wu at gmail.com
Tue Aug 16 23:49:58 CDT 2016

On Tue, Aug 16, 2016 at 11:31 PM, Charlie Monroe <charlie at charliemonroe.net>

> My original intention was to get rid of re-defining what should be the
> sequence sorted by. For example, if self.sorted { $0.age < $1.age } was at
> 10 places in code, I would not consider it a good coding technique and
> would definitely suggest the person to create a method for this -
> sortedByAge().
> self.sorted(.ascending) { $0.age } is a bit better, but I still feel that
> there is a lot of duplicate code and if one used this in 10 places over the
> project, a method for this should be created instead.
> Don't you agree that people.sortedByAge() reads better than
> self.sorted(.ascending) { $0.age }?
> What I was also aiming at is possibly something that could replace e.g.
> NSSortDescriptor, which can be handy in the UI, but requires dynamic
> (@objc) properties in order to work.
> What I'm suggesting, would also emit a function symbol for sorting the
> array by a particular key, so the sorting could actually be dynamic -
> supply a key (using #keyPath()) which is @sortable, given name mangling is
> stable in Swift 4, you can create the well-defined function symbol name,
> make a lookup via dyld and call it.
> Note that the NSSortDescriptor is just an example and given most of my
> development is on macOS, I use bindings and NSArrayController where the
> sort descriptors are fairly common unlike with iOS... But the usage of this
> can be extended to many other areas given that you *know* that there is a
> function out there, with that particular signature that will sort the
> array...
That does not strike me as a facility I would want. It seems like a lot of
special code to generate a wrapper for a very specific single line of code.

On Aug 17, 2016, at 12:45 AM, Xiaodi Wu <xiaodi.wu at gmail.com> wrote:
> On Tue, Aug 16, 2016 at 5:35 PM, Anton Zhilin <antonyzhilin at gmail.com>
> wrote:
>> What we need here is  sort_by  from Ruby. How about adding these
>> overloads?
>> func sort<U: Comparable>(by: (T) -> U)
>> func sorted<U: Comparable>(by: (T) -> U) -> [T]
> I'd be in favor. We'd need another name, since the current closure
> predicate is already standardized to `by:`.
> (Or, as I propose above, once `Ordering` comes to the stdlib, we can just
> have it as `func sort<U: Comparable>(_ ordering: Ordering, by: (T) -> U)`,
> called like `sort(.ascending) { $0.age }`.)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160816/4dc5061e/attachment.html>

More information about the swift-evolution mailing list