[swift-evolution] [Discussion] Sortable Attribute

Charlie Monroe charlie at charliemonroe.net
Tue Aug 16 15:51:18 CDT 2016


Hi there,

I'm not really sure whether this is appropriate, considering that Swift 4 should be basically focusing purely on ABI compatibility and a few other issues mentioned by Chris, but I've been thinking about this for some time and would make a lot of lives easier, so it could be part of 3.x.

I've written a proposal draft here: https://gist.github.com/charlieMonroe/0752cd61f7937f714b689137daf9de21

In brevity:

Currently, if you want consistent sorting of some entities, you either declare them Comparable and decide under which key do they sort and then use entities.sorted().

Unfortunately, this isn't really clear under what key do the entities sort. For example:

class Person {
    var age: Int = 21
    var firstName: String = "John"
    var lastName: String = "Doe"
}

If this were Comparable, would it sort by first name, last name or age? What if you wanted to be able to sort using all the properties? You'd probably resort to writing an extension on sequence:

extension Sequence where Self.Iterator.Element: MyClass {
    func sortedByFirstName() -> [Self.Iterator.Element] {
        return self.sorted(isOrderedBefore: { $0.firstName < $1.firstName })
    }
    func sortedByLastName() -> [Self.Iterator.Element] {
        return self.sorted(isOrderedBefore: { $0.lastName < $1.lastName })
    }
    func sortedByAge() -> [Self.Iterator.Element] {
        return self.sorted(isOrderedBefore: { $0.age < $1.age })
    }
}

This is fairly tedious, however. What I propose is to add a @sortable attribute to properties, which would automatically generate the code for you. It - of course - requires the property to conform to Comparable...

Any thoughts on this?



More information about the swift-evolution mailing list