当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Swift Dictionary merge(_:uniquingKeysWith:)用法及代码示例


用法一

实例方法

merge(_:uniquingKeysWith:)

将给定序列中的键值对合并到字典中,使用组合闭包来确定任何重复键的值。

声明

mutating func merge<S>(
    _ other: S,
    uniquingKeysWith combine: (Value, Value) throws -> Value) rethrows where S : Sequence, S.Element == (Key, Value
)
Key 符合 Hashable 时可用。

参数

other

一系列键值对。

combine

为任何重复键获取当前值和新值的闭包。闭包返回最终字典所需的值。

详述

使用 combine 闭包选择要在更新字典中使用的值,或组合现有值和新值。当键值对与字典合并时,combine 闭包会调用遇到的任何重复键的当前值和新值。

此示例显示如何为任何重复键选择当前值或新值:


var dictionary = ["a": 1, "b": 2]


// Keeping existing value for key "a":
dictionary.merge(zip(["a", "c"], [3, 4])) { (current, _) in current }
// ["b": 2, "a": 1, "c": 4]


// Taking the new value for key "a":
dictionary.merge(zip(["a", "d"], [5, 6])) { (_, new) in new }
// ["b": 2, "a": 5, "c": 4, "d": 6]

可用版本

iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+

用法二

实例方法

merge(_:uniquingKeysWith:)

将给定的字典合并到这个字典中,使用组合闭包来确定任何重复键的值。

声明

mutating func merge(
    _ other: [Key : Value],
    uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows
Key 符合 Hashable 时可用。

参数

other

要合并的字典。

combine

为任何重复键获取当前值和新值的闭包。闭包返回最终字典所需的值。

详述

使用 combine 闭包选择要在更新字典中使用的值,或组合现有值和新值。由于 other 中的 key-values 对与此字典合并,因此使用遇到的任何重复键的当前值和新值调用 combine 闭包。

此示例显示如何为任何重复键选择当前值或新值:


var dictionary = ["a": 1, "b": 2]


// Keeping existing value for key "a":
dictionary.merge(["a": 3, "c": 4]) { (current, _) in current }
// ["b": 2, "a": 1, "c": 4]


// Taking the new value for key "a":
dictionary.merge(["a": 5, "d": 6]) { (_, new) in new }
// ["b": 2, "a": 5, "c": 4, "d": 6]

可用版本

iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+

相关用法


注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 Dictionary merge(_:uniquingKeysWith:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。