Swift 语言 集合的排序操作

Swift阿木 发布于 2025-05-28 12 次阅读


Swift 集合【1】排序操作【2】详解

在 Swift 中,集合(Collection)是一种非常重要的数据结构,它允许我们存储一系列有序或无序的元素。集合操作是编程中常见的需求,其中排序操作尤为重要。本文将围绕 Swift 中的集合排序操作展开,详细介绍各种排序方法及其应用。

Swift 提供了多种集合类型,如 Array【3】、Set【4】 和 Dictionary【5】 等。这些集合类型都支持排序操作,但具体的实现和性能各有不同。本文将重点介绍 Array 和 Set 的排序操作。

Array 排序

Array 是 Swift 中最常用的集合类型之一,它允许存储任意类型的元素。Array 提供了多种排序方法,包括:

1. `sorted()`

`sorted()` 方法返回一个新的 Array,其中元素按照默认顺序排列。默认顺序取决于元素类型:

- 对于 `Comparable【6】` 类型,默认顺序是升序。
- 对于 `String` 类型,默认顺序是字典序【7】

swift
let numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
let sortedNumbers = numbers.sorted()
print(sortedNumbers) // 输出: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

2. `sorted(by:)`

`sorted(by:)` 方法允许自定义排序规则。它接受一个闭包【8】,该闭包定义了排序逻辑。

swift
let names = ["Alice", "Bob", "Charlie", "David"]
let sortedNames = names.sorted { $0 > $1 }
print(sortedNames) // 输出: ["David", "Charlie", "Bob", "Alice"]

3. `sorted(by:)` 与 `@escaping【9】` 属性

在 Swift 5.5 及以后的版本中,`sorted(by:)` 方法支持 `@escaping` 属性,这意味着闭包可以在排序操作完成后继续执行。

swift
let numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
let sortedNumbers = numbers.sorted { $0 < $1 } { (index1, index2) in
print("Comparing (numbers[index1]) and (numbers[index2])")
}
print(sortedNumbers)
// 输出: Comparing 3 and 1
// 输出: Comparing 1 and 4
// 输出: Comparing 4 and 1
// 输出: Comparing 1 and 5
// 输出: Comparing 5 and 9
// 输出: Comparing 9 and 2
// 输出: Comparing 2 and 6
// 输出: Comparing 6 and 5
// 输出: Comparing 5 and 3
// 输出: Comparing 3 and 5
// 输出: Comparing 5 and 5
// 输出: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

4. `sorted(by:)` 与 `inPlace【10】` 参数

`sorted(by:)` 方法还支持 `inPlace` 参数,它允许在原数组上进行排序,从而节省内存。

swift
var numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
numbers.sort { $0 < $1 }
print(numbers) // 输出: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

Set 排序

Set 是一种无序集合,它不允许重复元素。在 Swift 中,Set 没有内置的排序方法,因为它的元素是无序的。我们可以通过将 Set 转换为 Array,然后对 Array 进行排序,来间接实现 Set 的排序。

swift
let numbersSet: Set = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
let sortedNumbersSet = Array(numbersSet).sorted()
print(sortedNumbersSet) // 输出: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

总结

Swift 提供了丰富的集合操作,其中排序操作是编程中不可或缺的一部分。本文详细介绍了 Swift 中 Array 和 Set 的排序操作,包括默认排序、自定义排序、原地排序【11】和间接排序【12】等。掌握这些排序方法,可以帮助我们更高效地处理数据,提高代码质量。