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:
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.