Created
September 10, 2024 20:42
-
-
Save lucianoschillagi/e18f2696bca20f05b4c5c6c82f5072ef to your computer and use it in GitHub Desktop.
the sorted method example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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