Sorting Custom Objects By Property Value In Swift

Sorting a sequence of custom elements can be tricky, but once we understand how the sorting algorithm (provided by the Swift standard library) works, it will be a straight forward task.

Consider the following code:

struct Person {
    let name: String
    let age: Int
}

let persons = [Person(name: "Alex", age: 20), Person(name: "Bob", age: 40), Person(name: "Patrick", age: 35)]

Let’s say you want to sort the items in the array by age, placing the youngest first and the oldest last.

To do that, you want to use the sorted(by:) method, let’s see how it works:

let youngerToOlderPersons = persons.sorted { $0.age < $1.age }

What happen is that the sorted method will run the predicate (in this case $0.age < $1.age) for each two elements in the sequence, the result of the predicate would lead to one of the following scenario:

  • If true: In this case the first element will be ordered before the second element.
  • If false: In this case the first element will be ordered after the second element.

After sorting, the elements should now display in ascendant order based on the age property.

youngerToOlderPersons.forEach { person in
    print(person.age) 
}
// Will display
// 20
// 35
// 40

What if you want to order the elements in descending order? You guessed it right, you will only need to change the less-than operator to greater-than operator.

let olderToYoungerPersons = persons.sorted { $0.age > $1.age }

In this case, the same predicate will execute, if the condition is true, the first element will be ordered before the second element, otherwise, it will be ordered after.

In this case, the output would be:

olderToYoungerPersons.forEach { person in
    print(person.age)
}
// Will display
// 40
// 35
// 20

See you in the next digest!


Discover more from SweetTutos

Subscribe to get the latest posts sent to your email.

Malek
Software craftsman with extensive experience in iOS and web development.