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 not 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 into 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.



Please enter your comment!
Please enter your name here