How to sort array of custom objects by property value in Swift?
How to sort array of custom objects by property value in Swift?
To sort an array of custom objects by a property value in Swift, you can use the sort(by:) or sorted(by:) methods provided by Swift's standard library. These methods allow you to define custom sorting logic using closures. Here’s a step-by-step guide on how to achieve this:
Define Your Custom Object:
First, define the custom object (struct or class) with the properties you want to sort by. For example, let's define a Person struct with firstName, lastName, and age properties.
struct Person {
let firstName: String
let lastName: String
let age: Int
}
Create an Array of Custom Objects:
Create an array of these custom objects.
var people = [
Person(firstName: "John", lastName: "Smith", age: 25),
Person(firstName: "Jane", lastName: "Doe", age: 35),
Person(firstName: "Bob", lastName: "Jones", age: 20)
]
Sort the Array Using sorted(by:):
Use the sorted(by:) method to sort the array based on a specific property. For example, to sort by age in ascending order:
let sortedPeople = people.sorted { $0.age < $1.age }
This will sort the people array by the age property in ascending order.
Sort the Array Using sort(by:):
If you want to sort the array in place (modifying the original array), use the sort(by:) method:
people.sort { $0.age < $1.age }
Here is a complete example demonstrating how to sort an array of Person objects by their age property:
struct Person {
let firstName: String
let lastName: String
let age: Int
}
var people = [
Person(firstName: "John", lastName: "Smith", age: 25),
Person(firstName: "Jane", lastName: "Doe", age: 35),
Person(firstName: "Bob", lastName: "Jones", age: 20)
]
// Sorting the array by age in ascending order
let sortedPeople = people.sorted { $0.age < $1.age }
// Printing the sorted array
for person in sortedPeople {
print("\(person.firstName) \(person.lastName), Age: \(person.age)")
}
For a more reusable approach, you can make your custom object conform to the Comparable protocol. This way, you can use the sort() method directly without needing to pass a closure every time.
Conform to Comparable:
Implement the Comparable protocol in your custom object.
struct Person: Comparable {
let firstName: Str...
middle