Câu hỏi phỏng vấn Swift
Câu hỏi

How to sort array of custom objects by property value in Swift?

Câu trả lời

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:

Step-by-Step Guide

  1. 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
    }
  2. 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)
    ]
  3. 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.

  4. 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 }

Example Code

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)")
}

Using Comparable Protocol

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.

  1. Conform to Comparable:
    Implement the Comparable protocol in your custom object.

    struct Person: Comparable {
        let firstName: Str...
middle

middle

Gợi ý câu hỏi phỏng vấn

middle

What is difference between as? , as! and as in Swift?

expert

What is the use of Hashable protocol?

middle

What is a good use case for an inout parameter?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào