Swift Set 与高阶函数
系统核对 Swift 无序去重集合 Set 的 Hashable 要求、可变原地运算与纯函数集合代数、子集/真子集/不相交判断,以及 map、filter、reduce、compactMap、flatMap、forEach、sorted、contains(where:) 链式数据处理。
学完这一章,你能够
- 系统核对 Swift 无序去重集合 Set 的 Hashable 要求、可变原地运算与纯函数集合代数、子集/真子集/不相交判断,以及 map、filter、reduce、compactMap、flatMap、forEach、sorted、contains(where:) 链式数据处理。
Set 创建、原地修改、集合代数与包含关系
`Set` 是存储无序、不重复元素的哈希集合,要求元素遵循 `Hashable` 协议(标准库基本类型均满足,全 `Hashable` 字段的结构体可自动合成)。用数组字面量初始化 `Set` 会自动去重(如 `[1, 2, 2, 3, 3, 3]` 变为 3 个元素);因哈希表遍历顺序不保证稳定,输出展示前应先调用 `sorted()`。高阶函数则指接收函数/闭包作为参数或返回函数的能力,广泛定义在 `Sequence`/`Collection` 上。
增删元素可用 `insert` 与 `remove`(`remove` 返回被删元素的可选值,元素不存在时返回 `nil`);以 `form` 开头的原地方法(`formUnion`、`formIntersection` 及 `subtract`)直接修改原集合而不创建副本。`Set(array)` 与 `Array(set)` 可在去重集合与有序数组间自由互转。
纯集合运算 `union`(并集)、`intersection`(交集)、`subtracting`(差集)与 `symmetricDifference`(对称差,即并集减交集)均返回全新 `Set` 而不改原集合。关系判定方法 `isSubset(of:)`、`isSuperset(of:)`、`isStrictSubset(of:)` 与 `isDisjoint(with:)` 返回 `Bool`:两集合相等时 `isSubset` 为 `true` 而 `isStrictSubset` 为 `false`,空集是任意集合(含自身)的子集,判无交集应直接调用 `isDisjoint(with:)`。
核心高阶函数:map、filter、reduce、compactMap 与 flatMap
`Sequence` 与 `Collection` 提供的八个高频高阶函数适用于数组、集合与字典。`map` 对每个元素应用变换闭包(可用 `$0` 简写)并返回等长新数组(对 `Set` 调用 `map` 同样返回 `Array`);`filter` 保留谓词返回 `true` 的元素。
`reduce` 将整个序列折叠为单个结果值,接收初始值与 `(累计值, 当前元素)` 闭包,既可写完整闭包也可直接传入运算符函数(如 `numbers.reduce(0, +)` 得 `15`),初始值类型决定了最终聚合结果的类型。
`compactMap` 在映射的同时自动过滤掉返回 `nil` 的项(如把 `["1", "2", "invalid", "4"]` 转为 `[1, 2, 4]`,避免得到 `[Int?]`);`flatMap` 则将“集合的集合”或拆分出的子序列展平一层(如 `[[1,2],[3,4],[5]] -> [1,2,3,4,5]`)。两者分工明确:可选值去空用 `compactMap`,嵌套集合拍平用 `flatMap`。
forEach、sorted、contains(where:) 与链式调用
`forEach` 仅用于遍历产生副作用而无返回值(`Void`);`sorted()` / `sorted(by:)` 始终返回排序后的新数组而不改原集合;`contains(where:)` 判断是否存在满足条件的元素。将这些方法按每行一步的方式串联即可写出清晰的声明式流水线:例如 `(1...10).filter { $0 % 2 == 0 }.map { $0 * $0 }.reduce(0, +)` 精确得出 `220`,对词表去重转大写排序拼接得出 `"KOTLIN, RUST, SWIFT"`;若单行嵌套过复杂则应拆为具名中间变量。
Set 与高阶函数常见问答
四条实践原则:频繁判存在(`O(1)` 平均查找)、去重或做集合代数选 `Set`,保序或允许重复选 `Array`;需要产出新数组用 `map`,只需副作用用 `forEach`;`Set` 底层为随机化哈希表,需固定输出应 `sorted()`;自定义类型存入 `Set` 须遵循 `Hashable`,若手写 `==` 与 `hash(into:)` 必须保证相等实例哈希值一致。本站离线校验器已核对全部集合运算与高阶流水线结果。
Swift Set 四种不可变集合代数运算
| 方法 | 运算 | 结果说明 |
|---|---|---|
| a.union(b) | 并集 | 包含 a 或 b 中出现的全部元素。 |
| a.intersection(b) | 交集 | 仅保留同时存在于 a 与 b 中的共有元素。 |
| a.subtracting(b) | 差集 | 保留在 a 中但不在 b 中的元素。 |
| a.symmetricDifference(b) | 对称差 | 保留仅在 a 或仅在 b 中出现的元素(并集去交集)。 |
Swift 集合八个常用高阶函数速查
| 函数 | 作用 | 返回值 |
|---|---|---|
| map | 按闭包规则逐一映射每个元素 | 等长新数组 |
| filter | 筛选闭包返回 true 的元素 | 新数组 |
| reduce | 以初始值将全部元素折叠聚合 | 单个聚合值 |
| compactMap | 变换元素并丢弃结果为 nil 的项 | 非可选元素新数组 |
| flatMap | 映射并将嵌套集合展平一层 | 新数组 |
| forEach | 逐项执行副作用,不收集结果 | Void |
| sorted | 按默认或自定义比较器排序 | 新数组 |
| contains(where:) | 判断是否存在满足谓词的元素 | Bool |
运行离线 Python 校验:Swift Set 集合代数、包含关系与八大高阶函数链式管道
"""Offline CPython 3.12.14 semantic verifier for Swift Set & Higher-Order Functions (CH35)."""
import json
from functools import reduce
def swift_set_remove(s: set, elem):
if elem in s:
s.remove(elem)
return elem
return None
def case_set_creation_mutation_and_algebra():
langs = {"Swift", "Kotlin", "Rust"}
langs.add("Go")
dedup = sorted({1, 2, 2, 3, 3, 3})
s = {1, 2, 3}
s.add(4)
s.discard(1)
s |= {5, 6} # formUnion
s &= {2, 3, 5} # formIntersection
s -= {3} # subtract
tags = {"SWIFT", "swift"}
rem_ok = swift_set_remove(tags, "swift")
rem_miss = swift_set_remove(tags, "missing")
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
actual = {
"langs_count": len(langs),
"contains_swift": "Swift" in langs,
"contains_python": "Python" in langs,
"langs_sorted": sorted(langs),
"dedup": dedup,
"in_place_ops": sorted(s),
"remove_results": [rem_ok, rem_miss or "不存在"],
"union": sorted(a | b),
"intersection": sorted(a & b),
"subtracting": sorted(a - b),
"symmetric_difference": sorted(a ^ b),
}
expected = {
"langs_count": 4,
"contains_swift": True,
"contains_python": False,
"langs_sorted": ["Go", "Kotlin", "Rust", "Swift"],
"dedup": [1, 2, 3],
"in_place_ops": [2, 5],
"remove_results": ["swift", "不存在"],
"union": [1, 2, 3, 4, 5, 6],
"intersection": [3, 4],
"subtracting": [1, 2],
"symmetric_difference": [1, 2, 5, 6],
}
return {
"name": "set_creation_mutation_and_algebra",
"summary": "Verify Set deduplication, in-place form* operations, optional remove return, and pure union/intersection/subtracting/symmetricDifference.",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_set_relations():
small = {"Swift"}
big = {"Swift", "Kotlin", "Rust"}
same = {"Swift", "Kotlin", "Rust"}
empty: set[str] = set()
actual = {
"is_subset": small <= big,
"is_superset": big >= small,
"is_strict_subset": small < big,
"is_disjoint": big.isdisjoint({"Go"}),
"equal_is_subset": big <= same,
"equal_is_strict_subset": big < same,
"empty_is_subset_of_all": empty <= big and empty <= empty,
}
expected = {
"is_subset": True,
"is_superset": True,
"is_strict_subset": True,
"is_disjoint": True,
"equal_is_subset": True,
"equal_is_strict_subset": False,
"empty_is_subset_of_all": True,
}
return {
"name": "set_relations_subset_disjoint",
"summary": "Verify isSubset, isSuperset, isStrictSubset (false on equal sets), isDisjoint, and empty-set subset property.",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_higher_order_core():
numbers = [1, 2, 3, 4, 5]
doubled = [x * 2 for x in numbers]
upper_names = [s.upper() for s in ["alpha", "swift"]]
evens = [x for x in numbers if x % 2 == 0]
set_map_lengths = sorted([len(x) for x in {"Swift", "Go", "Rust"}])
sum_val = reduce(lambda acc, x: acc + x, numbers, 0)
max_val = reduce(lambda acc, x: acc if acc > x else x, numbers, numbers[0])
raw = ["1", "2", "invalid", "4"]
compact_ints = []
for tok in raw:
try:
compact_ints.append(int(tok))
except ValueError:
pass
nested = [[1, 2], [3, 4], [5]]
flat_nums = [x for sub in nested for x in sub]
sentences = ["Hello Swift", "Welcome to BlueSky"]
flat_words = [w for s in sentences for w in s.split(" ")]
actual = {
"map_doubled": doubled,
"map_upper": upper_names,
"filter_evens": evens,
"set_map_lengths": set_map_lengths,
"reduce_sum": sum_val,
"reduce_max": max_val,
"compact_map": compact_ints,
"flat_map_nums": flat_nums,
"flat_map_words": flat_words,
}
expected = {
"map_doubled": [2, 4, 6, 8, 10],
"map_upper": ["ALPHA", "SWIFT"],
"filter_evens": [2, 4],
"set_map_lengths": [2, 4, 5],
"reduce_sum": 15,
"reduce_max": 5,
"compact_map": [1, 2, 4],
"flat_map_nums": [1, 2, 3, 4, 5],
"flat_map_words": ["Hello", "Swift", "Welcome", "to", "BlueSky"],
}
return {
"name": "higher_order_map_filter_reduce_compact_flat",
"summary": "Verify map, filter, reduce, compactMap (dropping nil), and flatMap (flattening nested sequences).",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_foreach_sorted_contains_chaining():
numbers = [1, 2, 3, 4, 5]
side_effects: list[str] = []
for n in numbers:
side_effects.append(f"元素: {n}")
desc_nums = sorted(numbers, reverse=True)
orgs = [("BlueSky", 2014), ("Google", 1998), ("Apple", 1976)]
by_year = [o[0] for o in sorted(orgs, key=lambda t: t[1])]
has_gt_4 = any(x > 4 for x in numbers)
has_gt_100 = any(x > 100 for x in numbers)
# Chained pipeline: (1...10).filter(even).map(square).reduce(0, +)
chain_sum = reduce(
lambda a, b: a + b,
[x * x for x in range(1, 11) if x % 2 == 0],
0,
)
words = ["Swift", "Kotlin", "Swift", "Rust"]
chain_summary = ", ".join(sorted([w.upper() for w in set(words)]))
actual = {
"foreach_count": len(side_effects),
"sorted_desc": desc_nums,
"sorted_orgs": by_year,
"contains_gt_4": has_gt_4,
"contains_gt_100": has_gt_100,
"chain_even_square_sum": chain_sum,
"chain_dedup_upper_joined": chain_summary,
}
expected = {
"foreach_count": 5,
"sorted_desc": [5, 4, 3, 2, 1],
"sorted_orgs": ["Apple", "Google", "BlueSky"],
"contains_gt_4": True,
"contains_gt_100": False,
"chain_even_square_sum": 220,
"chain_dedup_upper_joined": "KOTLIN, RUST, SWIFT",
}
return {
"name": "foreach_sorted_contains_and_chaining",
"summary": "Verify forEach side-effects, sorted(by:), contains(where:), and multi-stage functional pipelines.",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main() -> None:
report = {
"version": "CPython 3.12.14 offline Swift 5/6 semantic verifier (swiftc absent)",
"cases": [
case_set_creation_mutation_and_algebra(),
case_set_relations(),
case_higher_order_core(),
case_foreach_sorted_contains_chaining(),
],
}
print(json.dumps(report, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 核对 Set 原地与纯函数四则代数、真子集区分相等集合、compactMap 去空与 flatMap 拍平,以及 (1...10) 偶平方和 220 与去重排序拼接。
所需环境:Windows x64、CPython 3.12.14 离线 Swift 5/6 语义校验器(本机未安装 swiftc / Xcode / SwiftPM)。
当前源码 SHA256:73bdbf1b7ad2cddbaa2f1ca9478110c9bff6a54197d03152b3f591a5a040e401
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 Swift 5/6 语义校验器(本机未安装 swiftc / Xcode / SwiftPM)。
ZIP SHA256:9ee17c81e8bebf56c325adeeb46e046f3b87859e10a34223b77fb65f05ba835b
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么处理“字符串数组转整数并忽略非法字符串”应使用 compactMap 而不是 map 或 flatMap?
展开参考解答
map 会保留转换失败的 nil 得到 [Int?];flatMap 语义用于展平嵌套集合(集合的集合);compactMap 专门用于变换并过滤可选结果中的 nil,直接得到干净的 [Int]。