Sort Collections Even Easier In Swift
Are you tired of using closure to define comparison strategy or the sort method multiple times for sorting collections? Here is the Solution😎
Introduction
There are many ways to sort an array in swift; one way is to use the sort method on the MutableCollection protocol.
Since now the method which we used was this:
Or this:
Or even the harder way:
So this pure function takes a closure to handle its task, but what if there was another way except using closures.
And Here it comes, The SortComparator.
What is SortComparator?
SortCamparator is a protocol in which every object that conforms to it provides a comparison algorithm and storage for the sort order to use when comparing.
There are two prepared types(thanks to apple) to use:
1 . KeyPathComparator
2. SortDescriptor
Yeah, you heard me SortDescriptor is now a part of the Swift standard library and can be used instead of old-school NSSortDescriptor. But it requires that the Comparable Type inherits NSObject and that the properties should be visible to the Objective-C runtime.
Yeah, Old-School Apple!!!!
I am going to skip SortDescriptor for the sake of not exposing the variables to objc runtime and using struct. So Let’s see the example of how to use KeyPathComparator:
Suppose we have this data source and we want to sort it.
Here is the way to use KeyPathComparator, easy peasy. Specify the keyPath of the property on which the sort should be based. The order is also set to reverse.
How about several KeyPath to be used in sort?
No problem!!🥳
Bonus Part
The exciting part is that KeyPathComparator also accepts another SortCamparator to compare the specified property if it is not comparable. It could be helpful when one or many custom types (maybe of kind collection) are composited inside each other.
Let’s see an example:
Here we aim to sort players by their scores, but score property is a collection, so we should clarify how to compare it. So another KeyPathComparator is used and sorted by the array's first value. It can be seen in the result that our players are sorted based on the first score they had.
I hope you enjoyed it, and it was helpful🫠
Until the Next article. Byeee😁👋🏻