Sort elements based on a property value using KeyPathComparator
If we have an array of elements in Swift and we need to sort it based on a specific property, we can't use the simple sorted() method.
For example, we might want to sort our ingredients array based on their sortOrder
property.
struct Ingredient {
let name: String
let sortOrder: Int
}
let ingredients = [
Ingredient(name: "cheese", sortOrder: 2),
Ingredient(name: "potato", sortOrder: 1),
Ingredient(name: "cream", sortOrder: 3)
]
We could use sorted(by:) method that accepts a closure, and define the comparison logic ourselves.
let sortedIngredients = ingredients
.sorted { ingredient1, ingredient2 in
ingredient1.sortOrder < ingredient2.sortOrder
}
But I've always found this method too verbose for such a common task.
Another way to approach it would be to use KeyPathComparator introduced in Foundation in iOS 15. We can pass the comparator created with a key path to a particular property to sorted(using:)
method.
let sortedIngredients = ingredients
.sorted(using: KeyPathComparator(\.sortOrder))
By default this will sort the elements in ascending order. If we want to sort our array in descending order instead, we can indicate reverse
order when creating the comparator.
let sortedIngredients = ingredients.sorted(
using: KeyPathComparator(\.sortOrder, order: .reverse))
I started using KeyPathComparator
only recently, but I find it easier to use than the sorted(by:)
method, and I think it makes the sorting logic clearer to read.
If you're an experienced Swift developer looking to learn advanced techniques, check out my latest book Swift Gems. It’s packed with tips and tricks focused solely on the Swift language and Swift Standard Library. From optimizing collections and handling strings to mastering asynchronous programming and debugging, "Swift Gems" provides practical advice that will elevate your Swift development skills to the next level. Grab your copy and let's explore these advanced techniques together.