我想弄清楚如何使用Swift字典的“合并”功能。我对这些文档感到困惑,我想了解一下如何阅读这些文档。
https://developer.apple.com/documentation/swift/dictionary/3127173-merging
在文档中,API声明如下所示:
func merging(_ other: [Key : Value], uniquingKeysWith
combine: (Value, Value) throws -> Value) rethrows -> [Key : Value]它显式地显示闭包有一个标签“uniquingKeysWith`”,然而,文档中的示例根本没有引用闭包参数标签!实际上,这个示例似乎忽略了很多API声明(例如返回值)。
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]我想在闭包中进行按键处理,这个例子表明ist是不可能的。具体来说,我希望在otherDictionary中删除零值,并用非零值覆盖dictionary值。
我想我想要进行筛选,实际上我可以在将KVP交给filter()函数之前,先用零值删除键,但如果可能的话,我宁愿只在一个闭包中这样做。
发布于 2022-03-12 04:33:16
文档非常清楚。上面写着
…将使用当前和新的值调用组合闭包,以处理遇到的任何重复键。
只有发生在中的键--两个字典--都在闭包中进行处理。
在本例中,对键a和b调用闭包,并分别返回current (表示dictionary)和new (表示otherDictionary)的更高值。
let dictionary = ["a": 1, "b": 4, "c": 4]
let otherDictionary = ["a": 3, "b": 2, "d": 5]
let keepingHighest = dictionary.merging(otherDictionary)
{ (current, new) in
print(current, new) // prints 4 2 and 1 3
return max(current, new)
}
// ["c": 4, "b": 4, "d": 5, "a": 3]字典中的nil值与系统搏斗,因为根据定义,nil值表示缺少键。
https://stackoverflow.com/questions/71446918
复制相似问题