let numbers = [5, 3, 8, 1, 2]
let sortedNumbers = numbers.sorted()
print(sortedNumbers) // 输出: [1, 2, 3, 5, 8]
let numbers = [5, 3, 8, 1, 2]
let sortedDescending = numbers.sorted(by: >)
print(sortedDescending) // 输出: [8, 5, 3, 2, 1]
let strings = ["apple", "pear", "banana", "grape"]
let sortedStrings = strings.sorted { $0.count < $1.count }
print(sortedStrings) // 输出: ["apple", "grape", "pear", "banana"]
struct Person {
let name: String
let age: Int
}
let people = [
Person(name: "Alice", age: 30),
Person(name: "Bob", age: 25),
Person(name: "Charlie", age: 35)
]
let sortedPeople = people.sorted { $0.age < $1.age }
for person in sortedPeople {
print("\(person.name): \(person.age)")
}
// 输出:
// Bob: 25
// Alice: 30
// Charlie: 35
var mutableNumbers = [5, 3, 8, 1, 2]
mutableNumbers.sort()
print(mutableNumbers) // 输出: [1, 2, 3, 5, 8]