Sort `Collection` using `KeyPath`

That doesn't work out very well using an array of Key Paths, but it does work if we use a type-erased SortDescriptor struct!

We'd get a call site that reads very nicely:

OS.supported.sorted(by: [
    SortDescriptor(\.yearReleased),
    SortDescriptor(\.name, using: String.caseInsensitiveCompare)])

compared to how you have have to express that today:

OS.supported.sorted { lhs, rhs in
    if (lhs.yearReleased == rhs.yearReleased) {
        return lhs.name.caseInsensitiveCompare(rhs.name) == .orderedAscending
    } else {
        return lhs.yearReleased < rhs.yearReleased
    }
}

It uses an implementation that looks like this.

1 Like