我的问题很简单,我想知道如何对两个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
]
]