Swift中的数组支持+ =运算符,将一个数组的内容添加到另一个数组.有没有一种简单的方法来为字典做到这一点?
例如:
var dict1 = ["a" : "foo"]
var dict2 = ["b" : "bar"]
var combinedDict = ... (some way of combining dict1 & dict2 without looping)
Run Code Online (Sandbox Code Playgroud) 我的问题很简单,我想知道如何对 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]
]
*/
Run Code Online (Sandbox Code Playgroud)
当dict1和dict2具有相同的键时,我希望该值被替换,但如果该值是另一个字典,我希望它被递归合并。
这是我想要的解决方案:
protocol Mergeable {
mutating func merge(obj: Self)
}
extension Dictionary: Mergeable { …Run Code Online (Sandbox Code Playgroud)