Swift 标准库增强全景:SE-0165《Dictionary 与 Set 增强》提案深度解析

原创2026-09-21 10:08:051,761 阅读
文章标签:文档编程语言

Swift 标准库增强全景:SE-0165《Dictionary 与 Set 增强》提案深度解析

SE-0165(Dictionary & Set Enhancements)是 Swift Evolution 历史上一个里程碑式的“综合提案”(omnibus proposal),它一次性为 Dictionary 补上了序列初始化、合并、带默认值的下标、字典专属 filter/mapValues、可见容量与元素分组等六类核心能力,同时为 Set 同步引入了同型 filter 与容量控制。本文以 proposals/0165-dict.md 为骨架,结合其前身提案 SE-0100 与后续演进提案 SE-0510,逐条还原每个 API 的设计动机、签名语义、使用示例与底层实现考量。读完本文,你将完整掌握今天 Swift 代码中 Dictionary/Set 这些高频 API 的来龙去脉,理解它们为什么以当前形态存在。

提案背景:一次“补课”式的标准库增强

在 Swift 4 之前,Dictionary 一直缺少一组与 Array、Set 对等的“序列化”能力。Array 和 Set 都有从元素序列直接构造实例的初始化器:Array 初始化器用于把其他序列转成“标准”集合类型,Set 初始化器则用于在函数式操作之后恢复集合运算能力。例如,对一个 Set 做过滤后,得到的是 LazyFilterCollection<Set<Int>> 而非 Set,必须再送回 Set 的序列初始化器才能恢复集合方法:

let numberSet = Set(1 ... 100)
let fivesOnly = numberSet.lazy.filter { $0 % 5 == 0 }

let fivesOnlySet = Set(numberSet.lazy.filter { $0 % 5 == 0 })
fivesOnlySet.isSubsetOf(numberSet) // true

而 Dictionary 没有类似的初始化器,于是“过滤一个字典并恢复字典类型”只能靠手写循环或 reduce,既啰嗦又无法从源序列做类型推断:

let numberDictionary = ["one": 1, "two": 2, "three": 3, "four": 4]
let evenOnly = numberDictionary.lazy.filter { (_, value) in
    value % 2 == 0
}

var viaIteration: [String: Int] = [:]
for (key, value) in evenOnly {
    viaIteration[key] = value
}

let viaReduce: [String: Int] = evenOnly.reduce([:]) { (cumulative, kv) in
    var dict = cumulative
    dict[kv.key] = kv.value
    return dict
}

向既有字典合并新元素同样是死胡同:Array 有 append(contentsOf:),Set 有 unionInPlace(_:),唯独 Dictionary 只能逐键赋值。这一现状在 Swift 4 时代终于得到系统性修复——SE-0165 于 2016 年提出、2017 年 1 月被接受,状态为 Implemented (Swift 4.0)。值得注意的是,它的前身提案 SE-0100 早已提出过类似设计但最终被撤回,SE-0165 是在其基础上吸取评审意见、重新组织后形成的成果。

官方对标准库“字典易用性”的重视也有迹可循:在 releases/swift-4_0.md 的 Swift 4 版本发布说明中,明确将“改进 Dictionary 的易用性”列为标准库改进的重点方向之一。

一、合并初始化器与合并方法(Merging Initializers and Methods)

1.1 序列初始化器:init(uniqueKeysWithValues:)

提案为 Dictionary 新增一个接受任意 (Key, Value) 元组序列的初始化器,签名如下:

init<S: Sequence where S.Iterator.Element == (key: Key, value: Value)>(
    uniqueKeysWithValues: S)

有了它,从键值对序列创建字典就和创建 Array、Set 一样简单:

let viaProposed = Dictionary(uniqueKeysWithValues: evenOnly)

与 Array.init(_:)、Set.init(_:) 一样,这是一个“全宽度”(full-width)初始化器:它带有 前置条件(precondition)——输入序列中的每个键必须唯一,一旦出现重复键就会触发运行时陷阱(trap)。因此当输入数据可能出现重复键时,必须改用下一节的合并初始化器。

该初始化器解锁了几类此前无法优雅表达的用法:

  • 从 DictionaryLiteral(类型本身,而非字面量)初始化:

    let literal: DictionaryLiteral = ["a": 1, "b": 2, "c": 3, "d": 4]
    let dictFromDL = Dictionary(uniqueKeysWithValues: literal)
    
  • 把数组转成“索引字典”(讨论帖中最受欢迎的用法):

    let names = ["Cagney", "Lacey", "Bensen"]
    let dict = Dictionary(uniqueKeysWithValues: names.enumerated().map { (i, val) in (i + 1, val) })
    // [2: "Lacey", 3: "Bensen", 1: "Cagney"]
    
  • 从两条 zip 起来的序列初始化:

    let letters = "abcdef".characters.lazy.map(String.init)
    let dictFromZip = Dictionary(uniqueKeysWithValues: zip(letters, 1...10))
    // ["b": 2, "e": 5, "a": 1, "f": 6, "d": 4, "c": 3]
    

    当时该用法受限于编译器缺陷 SR-922 无法直接编译,提案给出的临时绕过办法是在元素上补一个 .map {(key: $0, value: $1)}。该问题早已在后续编译器版本中修复,如今 zip 序列直接初始化已是日常写法。

1.2 合并初始化器:init(_:uniquingKeysWith:)

字典字面量在遇到重复键时会直接报错,上面的序列初始化器同样如此:

let duplicates: DictionaryLiteral = ["a": 1, "b": 2, "a": 3, "b": 4]
let letterDict = Dictionary(uniqueKeysWithValues: duplicates)
// error: Duplicate key found: "a"

但很多真实场景对重复键是“宽容”的——例如统计频率时我们希望把重复键对应的值累加。为此提案增加第二个初始化器,让调用者随序列一并提供一个合并闭包(combining closure),每当遇到重复键,就用“旧值 + 新值”算出最终值:

init<S: Sequence>(
    _ keysAndValues: S,
    uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows where S.Iterator.Element == (key: Key, value: Value)

注意 combine 闭包是 throws 的且整个初始化器声明为 rethrows——如果调用者传入的闭包可以抛错,则初始化器也会抛错;否则它保持不抛错,这一设计沿用至今。

典型用法:保留重复键的第一个值——

let letterDict2 = Dictionary(duplicates, uniquingKeysWith: { (first, _) in first })
// ["b": 2, "a": 1]

或者保留最大值(直接传 max 函数,Swift 会自动适配元参数):

let letterDict3 = Dictionary(duplicates, uniquingKeysWith: max)
// ["b": 4, "a": 3]

讨论帖中 Donnacha Oisín Kidney 贡献的 frequencies() 方法堪称合并初始化器的“教科书级”应用——把每个元素映射成 (元素, 1),再用 + 作为合并策略完成频次统计:

extension Sequence where Iterator.Element: Hashable {
    func frequencies() -> [Iterator.Element: Int] {
        return Dictionary(self.lazy.map { v in (v, 1) }, uniquingKeysWith: +)
    }
}
[1, 2, 2, 3, 1, 2, 4, 5, 3, 2, 3, 1].frequencies()
// [2: 4, 4: 1, 5: 1, 3: 3, 1: 3]

1.3 合并方法:merge(_:uniquingKeysWith:) 与 merging(_:uniquingKeysWith:)

除了初始化,提案还为 Dictionary 增加了就地修改与不可变返回两个方向的合并方法,用于把一段 (Key, Value) 序列合并进既有字典:

mutating func merge<S: Sequence>(
    _ other: S,
    uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows where S.Iterator.Element == (key: Key, value: Value)

func merging<S: Sequence>(
    _ other: S,
    uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows -> [Key: Value] where S.Iterator.Element == (key: Key, value: Value)

两个方法语义相同,区别仅在于:merge 原地修改调用者自身;merging 返回一个合并后的全新字典,调用者保持不变。

两个高频实战场景:

// 合并默认值(保留既有值)
let defaults: [String: Bool] = ["foo": false, "bar": false, "baz": false]
var options: [String: Bool] = ["foo": true, "bar": false]
options.merge(defaults) { (old, _) in old }
// options 现在是 ["foo": true, "bar": false, "baz": false]

// 循环累加计数
var bugCounts: [String: Int] = ["bees": 9, "ants": 112, ...]
while bugCountingSource.hasMoreData() {
    bugCounts.merge(bugCountingSource.countMoreBugs(), uniquingKeysWith: +)
}

结合前身提案 SE-0100 可以看清 API 命名的演变:SE-0100 曾使用 merge(contentsOf:combine:)、merged(with:combine:) 以及 init(merging:combine:) 的形式;SE-0165 在评审后统一为“参数标签 uniquingKeysWith: + merge/merging 动词”的现行形态,语义更直白(见后文“备选方案与设计权衡”)。

二、带默认值的键下标:subscript(key:default:)

字典迭代更新的经典痛点是“键可能不存在”。以统计字符串中字母频率为例,惯常写法要么判空、要么强制解包,既啰嗦又容易出错:

let source = "how now brown cow"
var frequencies: [Character: Int] = [:]
for c in source.characters {
    if frequencies[c] == nil {
        frequencies[c] = 1
    } else {
        frequencies[c]! += 1
    }
}

提案给出的方案是新增一个带 default 参数的下标,直接把默认值随键一起传入,下标返回类型也因此从 Optional<Value> 变为非可选 Value:

let source = "how now brown cow"
var frequencies: [Character: Int] = [:]
for c in source.characters {
    frequencies[c, default: 0] += 1
}

这段代码如今已是 Swift 社区统计频率的标准写法。提案还特别澄清了读取语义:作为 getter 访问该下标不会把默认值写入字典,下面两行完全等价:

let x = frequencies["a", default: 0]
let y = frequencies["a"] ?? 0

也就是说,default: 只影响返回值,不改变字典内容;真正的“写入默认值”发生在复合赋值(如 +=)通过 setter 写入时。从实现角度看,去掉 Optional 包装也为未来所有权模型下更高效的 modify 操作扫清了障碍——这是提案原文点明的一个前瞻性动机。

三、字典专属的 filter 与 mapValues

3.1 痛点:通用 map/filter 不适配字典

标准库的 map、filter 很强大,但用在字典上并不理想:大多数时候我们希望的结果是另一个字典而非键值对数组。即使借助第一节的序列初始化器,这种写法依然绕路且低效;而通用的 map 还要求变换函数接受并返回键值对,导致每次都必须手写闭包:

let numbers = ["one": 1, "two": 2, "three": 3, "four": 4]
let evens = Dictionary(numbers.lazy.filter { $0.value % 2 == 0 })!
// ["four": 4, "two": 2]
let strings = Dictionary(numbers.lazy.map { (k, v) in (k, String(v)) })!
// ["three": "3", "four": "4", "one": "1", "two": "2"]

3.2 方案:mapValues 与返回字典的 filter

提案为 Dictionary 新增两个专用方法:

1. mapValues——保留键、只变换值

映射键值对可能因键冲突而无法总是得到字典,但只映射值必然可以产生与原始字典底层布局一致的新字典:

let strings = numbers.mapValues(String.init)
// ["three": "3", "four": "4", "one": "1", "two": "2"]

mapValues 之所以比通用 map 高效,关键在于它无需重新哈希:新字典可以复用原字典的键存储区域,只对新值进行变换即可(详见 proposals/0165-dict.md 第 3 节)。

2. 返回 Dictionary 的 filter

过滤字典至多复制整个字典,不会产生键冲突,因此完全可以直接返回字典:

let evens = numbers.filter { $0.value % 2 == 0 }
// ["four": 4, "two": 2]

3.3 后续演进:SE-0510 的 mapKeyedValues

mapValues 并非终点。后续提案 SE-0510《Dictionary.mapValues 带键版本》 指出:当变换逻辑需要“键上下文”时,开发者只能退回到 init(uniqueKeysWithValues:) 或 reduce(into:),两者都无可避免地付出重新哈希(乃至重新分配存储)的性能代价。SE-0510 提议在既有 mapValues 之外新增 mapKeyedValues 方法,在存储迭代循环内把键连同值一起传给变换闭包,从而在保持 mapValues 性能特征的同时获得键上下文;该提案还讨论了在未来的语言模式下把 mapValues 之名让渡给带键版本的可能性。这可以看作是 SE-0165 所开创的“字典专属变换 API”思路的延续。

四、可见的字典容量:capacity 与 reserveCapacity(_:)

哈希集合的扩容代价远高于数组:数组扩容只需把元素整体搬到新内存,而字典扩容时每个键值对都必须单独搬移并重新计算键的哈希值以确定在新缓冲区中的位置。尽管字典采用指数增长策略来摊薄成本,但除了 init(minimumCapacity:) 之外,它始终没有暴露“预留容量”的途径;同时,“只要容量不变,添加键值对就不会使既有索引失效”这一保证也无法被用户主动利用,因为没有途径查看当前容量。

提案为 Dictionary 补齐了与可变集合一致的 capacity 属性与 reserveCapacity(_:) 方法:

var numbers = ["one": 1, "two": 2, "three": 3, "four": 4]
numbers.capacity   // 6
numbers.reserveCapacity(20)
numbers.capacity   // 24

语义说明(提案原文明确点出的两个“不等于”):

  • capacity 表示“不触发更大后备存储重新分配的前提下能容纳的元素个数”;
  • 由于哈希集合需要额外空槽来降低碰撞概率与代价,capacity 的数值不会等于后备存储的实际大小;
  • 调用 reserveCapacity(_:) 之后,容量“至少”不小于参数,但通常会更大——在当时的实现中,Dictionary 的后备存储大小始终是 2 的幂,所以示例中请求 20 得到 24(实际为 32 槽位按负载因子折算后的容量)。

这一特性与 Set 同时落地(见第六节),并为后来 Dictionary 在 reserveCapacity 上的持续优化(包括针对 init(minimumCapacity:) 的负载因子调整)奠定了基础。

五、序列元素分组:Dictionary(grouping:by:)

把序列元素按某个计算出的键分组,是社区长期呼吁的能力,SE-0165 把它作为最后一个字典相关特性纳入。新初始化器接收一个把每个元素转换为哈希类型 T 的闭包,产出的字典键类型为 T,值类型为 [Iterator.Element]:

let names = ["Patti", "Aretha", "Anita", "Gladys"]

// 按首字母分组
Dictionary(grouping: names, by: { $0.characters.first! })
// ["P": ["Patti"], "G": ["Gladys"], "A": ["Aretha", "Anita"]]

// 按名字长度分组
Dictionary(grouping: names) { $0.utf16.count }
// [5: ["Patti", "Anita"], 6: ["Aretha", "Gladys"]]

注意两个示例展示了闭包放置的两种合法形式:显式 by: 标签,或利用尾随闭包省略 by:。分组初始化器在实现上等价于“对每个元素求键 → 追加到对应分组数组”,由于键来自元素本身而非外部输入,天然不存在重复键冲突问题。Dictionary(grouping:by:) 至今仍是 Swift 标准库中做分组统计的主力 API。

六、同步应用到 Set 的改动

Set 与 Dictionary 共享大段实现代码,因此提案顺理成章地把其中对 Set 同样有价值的部分一并纳入:

  • Set 专属 filter:返回 Set 而非数组。其效果本质上是一个“基于谓词的 intersection”——保留满足条件的元素并恢复集合语义:

    let digits = Set(0..<10)
    let evens = digits.filter { $0 % 2 == 0 }   // 返回 Set<Int>
    
  • capacity 属性与 reserveCapacity(_:) 方法:动机与 Dictionary 完全相同,用于预分配存储、规避哈希集合扩容的高昂代价。

完整 API 一览(Detailed Design)

将上述新 API 汇总到一处,即为提案的“详细设计”部分。以下代码块(含文档注释)基本忠实于 proposals/0165-dict.md 原文,便于对照查阅;其中 reserveCapacity 在原文中被误写为 var 关键字,正确声明应为 func,本文按语义订正:

struct Dictionary<Key: Hashable, Value> {
    typealias Element = (key: Key, value: Value)

    // existing declarations

    /// Creates a new dictionary using the key/value pairs in the given sequence.
    /// If the given sequence has any duplicate keys, the result is `nil`.
    init<S: Sequence>(uniqueKeysWithValues: S) where S.Iterator.Element == Element

    /// Creates a new dictionary using the key/value pairs in the given sequence,
    /// using a combining closure to determine the value for any duplicate keys.
    init<S: Sequence>(
        _ keysAndValues: S,
        uniquingKeysWith combine: (Value, Value) throws -> Value
    ) rethrows where S.Iterator.Element == Element

    /// Creates a new dictionary where the keys are the groupings returned by
    /// the given closure and the values are arrays of the elements that
    /// returned each specific key.
    init<S: Sequence>(
        grouping values: S,
        by keyForValue: (S.Iterator.Element) throws -> Key
    ) rethrows where Value == [S.Iterator.Element]

    /// Merges the key/value pairs in the given sequence into the dictionary,
    /// using a combining closure to determine the value for any duplicate keys.
    mutating func merge<S: Sequence>(
        _ other: S,
        uniquingKeysWith combine: (Value, Value) throws -> Value
    ) rethrows where S.Iterator.Element == Element

    /// Returns a new dictionary created by merging the key/value pairs in the
    /// given sequence into the dictionary, using a combining closure to determine
    /// the value for any duplicate keys.
    func merging<S: Sequence>(
        _ other: S,
        uniquingKeysWith combine: (Value, Value) throws -> Value
    ) rethrows -> [Key: Value] where S.Iterator.Element == Element

    /// Accesses the element with the given key, or the specified default value,
    /// if the dictionary doesn't contain the given key.
    subscript(key: Key, default defaultValue: Value) -> Value { get set }

    /// Returns a new dictionary containing the key/value pairs that satisfy
    /// the given predicate.
    func filter(_ isIncluded: (Key, Value) throws -> Bool) rethrows -> [Key: Value]

    /// Returns a new dictionary containing the existing keys and the results of
    /// mapping the given closure over the dictionary's values.
    func mapValues<T>(_ transform: (Value) throws -> T) rethrows -> [Key: T]

    /// The number of key/value pairs that can be stored by the dictionary without
    /// reallocating storage.
    var capacity: Int { get }

    /// Ensures that the dictionary has enough storage for `capacity` key/value
    /// pairs.
    func reserveCapacity(_ capacity: Int)
}

struct Set<Element: Hashable> {
    // existing declarations

    /// Returns a new set containing the elements that satisfy the given predicate.
    func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> Set

    /// The number of elements that can be stored by the set without
    /// reallocating storage.
    var capacity: Int { get }

    /// Ensures that the set has enough storage for `capacity` elements.
    func reserveCapacity(_ capacity: Int)
}

为便于快速检索,将全部新增符号整理如下:

类型 新增 API 关键语义
Dictionary init(uniqueKeysWithValues:) 键必须唯一,重复键触发 trap
Dictionary init(_:uniquingKeysWith:) 用合并闭包处理重复键
Dictionary init(grouping:by:) 按闭包计算的键分组
Dictionary mutating func merge(_:uniquingKeysWith:) 就地合并
Dictionary func merging(_:uniquingKeysWith:) 返回合并后的新字典
Dictionary subscript(key:default:) 非可选返回值,getter 不写入默认值
Dictionary func filter(_:) -> [Key: Value] 返回字典而非数组
Dictionary func mapValues<T>(_:) 只变换值,复用键存储
Dictionary var capacity / func reserveCapacity(_:) 可见容量与预分配
Set func filter(_:) -> Set 谓词式 intersection
Set var capacity / func reserveCapacity(_:) 可见容量与预分配

备选方案与设计权衡(Alternatives Considered)

SE-0165 的评审过程留下了丰富的设计取舍记录,理解这些权衡有助于把握 API 的最终形态:

放弃“可失败初始化器”方案

早期版本曾把 init(uniqueKeysWithValues:) 设计为**可失败(failable)**初始化器,遇到重复键时返回 nil。但评审后认为该形态只适合“已知键唯一”的场景,一旦输入可能含重复键,可失败返回没有可行的恢复路径,最终方案改为“前置条件 + trap”。这也是其前身 SE-0100(当时为 init?(_ keysAndValues:))被撤回重做的重要原因之一。

放弃顶层函数 first(_:_:) / last(_:_:)

早期草案曾考虑为标准库增加 first(_:_:) 与 last(_:_:) 两个顶层函数,分别返回第一、第二个参数,供合并闭包位置直接传入:

let firstWins = Dictionary(merging: duplicates, mergingValues: first)
// ["b": 2, "a": 1]

作为替代,还考虑过引入 MergeCollisionStrategy 枚举(useFirst / useLast)并为其增加若干合并重载:

extension Dictionary {
    /// The strategy to use when merging a sequence of key-value pairs into a dictionary.
    enum MergeCollisionStrategy {
        case useFirst
        case useLast
    }

    init<S: Sequence>(
        merging keysAndValues: S,
        mergingValues strategy: MergeCollisionStrategy
    )
    // other merging overloads
}

最终两个方向都未采纳:前者把本应内聚的合并行为散落到顶层函数,后者需要额外维护三组重载。uniquingKeysWith: 的通用闭包方案在表达力与 API 面之间取得了更好的平衡。

remove(at:) 改动被推迟

早期版本还包含对 Dictionary/Set 的 remove(at:) 的改动——使其同时返回被移除元素与迭代序列中的下一个有效索引,从而支持高效的原地删除:

var i = dict.startIndex
while i != dict.endIndex {
    if shouldRemove(dict[i]) {
        (_, i) = dict.remove(at: i)
    } else {
        dict.formIndex(after: &i)
    }
}

由于该改动对既有代码影响面更大,被整体推迟到后续单独提案处理,未随 SE-0165 落地。

命名与形态的最终演变

被评审的版本使用过一套不同的拼写:init(_ keysAndValues:)、init(merging:mergingValues:)、mutating func merge(_:mergingValues:)、func merged(with:mergingValues:);分组能力也曾被提议为 Sequence 协议上的 grouped(by:) 方法。接受提案的评审结论(rationale)解释了这些变更的原因,最终定型为我们今天熟悉的 uniqueKeysWithValues: / uniquingKeysWith: / grouping:by: 命名体系。

源码兼容性(Source Compatibility)

所有新增 API 都是纯增量的,整体兼容负担极小。唯一的潜在破坏点在于 Dictionary/Set 新增了“同型返回”的 filter(_:)——如果既有代码依赖旧行为(filter 返回数组),例如:

let digits = Set(0..<10)
let evens = digits.filter { $0 % 2 == 0 }
functionThatTakesAnArray(evens)

这段代码在 Swift 4 下将因类型变化而无法编译。为缓解影响,提案设计了按语言模式分发的重载:Swift 3 模式下继续提供返回数组的旧版 filter,Swift 4 模式下启用返回 Set 的新版:

extension Set {
    @available(swift, obsoleted: 4)
    func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> [Element]

    @available(swift, introduced: 4)
    func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> Set<Element>
}

这套“obsoleted + introduced”策略后来成为标准库平滑过渡返回类型变化的标准手法。

结语:一份提案如何塑造今天的 Swift 集合编程

回顾 SE-0165,它解决的不是某一个孤立痛点,而是把 Dictionary 从“只能字面量构造 + 逐键操作”的原始形态,提升为与现代 Array、Set 能力对等的集合类型。今天几乎每个 Swift 工程都会用到 Dictionary(uniqueKeysWithValues:)、merging(_:uniquingKeysWith:)、dict[key, default: 0]、mapValues、Dictionary(grouping:by:) 与 reserveCapacity——它们全部出自这份 Swift 4.0 时代的综合提案,并经由 SE-0510 等后续提案继续演进。

如需深入原文,可直接阅读仓库中的 SE-0165 提案全文;其前身设计可对照已撤回的 SE-0100,后续延伸可见 SE-0510《Dictionary.mapValues 带键版本》,而该提案在 Swift 4.0 发布版中的定位可参阅 releases/swift-4_0.md。

登录后查看全文
swift-evolution