Skip to content

Instantly share code, notes, and snippets.

@lucianoschillagi
Created September 10, 2024 20:42
Show Gist options
  • Save lucianoschillagi/e18f2696bca20f05b4c5c6c82f5072ef to your computer and use it in GitHub Desktop.
Save lucianoschillagi/e18f2696bca20f05b4c5c6c82f5072ef to your computer and use it in GitHub Desktop.
the sorted method example
import Foundation
class Person {
let name: String
let age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
let people = [
Person(name: "Alice", age: 25),
Person(name: "Bob", age: 20),
Person(name: "Charlie", age: 30)
]
// Sorting by age using a closure
let sortedByAge = people.sorted { (personA, personB) -> Bool in
return personA.age < personB.age
}
// Sorting by name using a closure
let sortedByName = people.sorted { (personA, personB) -> Bool in
return personA.name < personB.name
}
// Print sorted names by age
for person in sortedByAge {
print("\(person.name): \(person.age)")
}
// Print sorted names by name
for person in sortedByName {
print("\(person.name): \(person.age)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment