[swift-evolution] [Discussion] Sortable Attribute

Charlie Monroe charlie at charliemonroe.net
Tue Aug 16 23:31:13 CDT 2016


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...


> 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 <mailto: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/20160817/bc902cbd/attachment.html>


More information about the swift-evolution mailing list