Sobes.tech
Junior — Middle

Can you give an example of a data sorting method?

sobes.tech AI

Answer from AI

In iOS, the sorted(by:) method is often used to sort data in arrays. It takes a closure that defines the order of the elements.

Example of sorting an array of numbers in ascending order:

let numbers = [5, 2, 9, 1, 7]
let sortedNumbers = numbers.sorted(by: { $0 < $1 })
print(sortedNumbers) // [1, 2, 5, 7, 9]

To sort an array of objects by a specific property:

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

let people = [
    Person(name: "Ivan", age: 30),
    Person(name: "Anna", age: 25),
    Person(name: "Pyotr", age: 35)
]

let sortedByAge = people.sorted { $0.age < $1.age }
// Sorted by age: Anna, Ivan, Pyotr
Can you give an example of a data sorting method? — iOS - sobes.tech