【发布时间】:2016-01-01 00:15:11
【问题描述】:
我的问题很简单,我想知道如何对 2 个 Swift 词典(不是 NSDictionary)进行深度合并。
let dict1 = [
"a": 1,
"b": 2,
"c": [
"d": 3
],
"f": 2
]
let dict2 = [
"b": 4,
"c": [
"e": 5
],
"f": ["g": 6]
]
let dict3 = dict1.merge(dict2)
/* Expected:
dict3 = [
"a": 1,
"b": 4,
"c": [
"d": 3,
"e": 5
],
"f": ["g": 6]
]
*/
当dict1 和dict2 具有相同的键时,我希望该值被替换,但如果该值是另一个字典,我希望它被递归合并。
这是我想要的解决方案:
protocol Mergeable {
mutating func merge(obj: Self)
}
extension Dictionary: Mergeable {
// if they have the same key, the new value is taken
mutating func merge(dictionary: Dictionary) {
for (key, value) in dictionary {
let oldValue = self[key]
if oldValue is Mergeable && value is Mergeable {
var oldValue = oldValue as! Mergeable
let newValue = value as! Mergeable
oldValue.merge(newValue)
self[key] = oldValue
} else {
self[key] = value
}
}
}
}
但它给了我错误Protocol 'Mergeable' can only be used as a generic constraint because it has Self or associated type requirements
编辑: 我的问题与Swift: how to combine two Dictionary instances? 不同,因为那不是深度合并。
使用该解决方案,它将产生:
dict3 = [
"a": 1,
"b": 4,
"c": [
"e": 5
]
]
【问题讨论】:
-
那个不是深度合并。
-
在 Swift 中,你心目中的字典类型到底是什么?
-
它可以是任何东西,这就是问题所在,它不一定只有 2 层深,只有字符串和数字。
-
你不能有任何东西的 Swift 字典。请回答问题。
标签: swift dictionary