WWDC24 deal: 30% off our Swift and SwiftUI books! Learn more ...WWDC24 deal:30% off our Swift and SwiftUI books >>
Quick Tip Icon
Quick Tip

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.

Books by Natalia PanferovaBooks by Natalia Panferova
WWDC24: 30% off all books!
  • Swift Gems

    100+ tips to take your Swift code to the next level

  • Integrating SwiftUI into UIKit Apps

    A detailed guide on gradually adopting SwiftUI in UIKit projects

The offer is active until the 16th of June.