Swift Dictionary merging(_:uniquingKeysWith:)用法及代码示例
用法一
实例方法
merging(_:<wbr>uniquing<wbr>Keys<wbr>With:)
通过将给定字典合并到此字典中来创建字典,使用组合闭包来确定重复键的值。
声明
func merging(
_ other: [Key : Value],
uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows -> [Key : Value]
当 Key
符合 Hashable
时可用。
返回值
包含此字典和 other
的组合键和值的新字典。
参数
other
要合并的字典。
combine
为任何重复键获取当前值和新值的闭包。闭包返回最终字典所需的值。
详述
使用 combine
闭包选择要在返回字典中使用的值,或组合现有值和新值。随着other
中的键值对与此字典合并,combine
闭包会调用遇到的任何重复键的当前值和新值。
此示例显示如何为任何重复键选择当前值或新值:
let dictionary = ["a": 1, "b": 2]
let otherDictionary = ["a": 3, "b": 4]
let keepingCurrent = dictionary.merging(otherDictionary)
{ (current, _) in current }
// ["b": 2, "a": 1]
let replacingCurrent = dictionary.merging(otherDictionary)
{ (_, new) in new }
// ["b": 4, "a": 3]
用法二
实例方法
merging(_:<wbr>uniquing<wbr>Keys<wbr>With:)
通过将序列中的键值对合并到字典中来创建字典,使用组合闭包来确定重复键的值。
声明
func merging<S>(
_ other: S,
uniquingKeysWith combine: (Value, Value) throws -> Value) rethrows -> [Key : Value] where S : Sequence, S.Element == (Key, Value
)
当 Key
符合 Hashable
时可用。
返回值
包含此字典和 other
的组合键和值的新字典。
参数
other
一系列键值对。
combine
为任何重复键获取当前值和新值的闭包。闭包返回最终字典所需的值。
详述
使用 combine
闭包选择要在返回字典中使用的值,或组合现有值和新值。当键值对与字典合并时,combine
闭包会调用遇到的任何重复键的当前值和新值。
此示例显示如何为任何重复键选择当前值或新值:
let dictionary = ["a": 1, "b": 2]
let newKeyValues = zip(["a", "b"], [3, 4])
let keepingCurrent = dictionary.merging(newKeyValues) { (current, _) in current }
// ["b": 2, "a": 1]
let replacingCurrent = dictionary.merging(newKeyValues) { (_, new) in new }
// ["b": 4, "a": 3]
Swift Dictionary merge(_:uniquingKeysWith:)用法及代码示例
用法一
实例方法
merge(_:<wbr>uniquing<wbr>Keys<wbr>With:)
将给定序列中的键值对合并到字典中,使用组合闭包来确定任何重复键的值。
声明
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]
用法二
实例方法
merge(_:<wbr>uniquing<wbr>Keys<wbr>With:)
将给定的字典合并到这个字典中,使用组合闭包来确定任何重复键的值。
声明
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]