Tuesday, August 30, 2016

Sort Descriptors in Swift

Chris Eidhof (tweet):

A sort descriptor uses two runtime features of Objective-C: the key is a key path, and key-value coding is used to lookup the value of that key at runtime. […]

This is a pretty cool use of runtime programming, especially when you realize the array of sort descriptors can be built at runtime, say based on a user clicking a column heading.


Rather than copying and pasting, we can define a function with an interface that is much like NSSortDescriptor, but without the runtime programming. This function takes a key and a comparison method, and returns a sort descriptor (the function, not the class NSSortDescriptor). Here, key is not a string, but a function. To compare two keys, we use a function isOrderedBefore. Finally, the result type is a function as well, even though that is slightly obscured by the typealias.

However, he does not show how to achieve functionality equivalent to NSSortDescriptor, e.g. pulling the identifier out of a table column and sorting by that. Of course, this is trivial by leaning on the Objective-C runtime, but can it be done efficiently and concisely with a pure Swift object?

One drawback of the function-based approach is that functions are opaque. We can take an NSSortDescriptor, print it to the console, and we get some information about the sort descriptor: the key path, the selector name and whether it’s ascending.

This also prevents straightforwardly persisting the sort descriptor or translating it into a database query.

1 Comment RSS · Twitter

Not sure if I'm willing to wrap my head around this, just to get something as trivial as NSSortDescriptor to work...

Maybe I'm just getting old...

Leave a Comment