相关疑难解决方法(0)

如何将项目词典添加到另一个词典中

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)

dictionary swift

165
推荐指数
17
解决办法
10万
查看次数

如何深度合并 2 个 Swift 词典

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

dict1dict2具有相同的键时,我希望该值被替换,但如果该值是另一个字典,我希望它被递归合并。

这是我想要的解决方案:

protocol Mergeable {

    mutating func merge(obj: Self)

}

extension Dictionary: Mergeable { …
Run Code Online (Sandbox Code Playgroud)

dictionary swift

6
推荐指数
2
解决办法
1176
查看次数

标签 统计

dictionary ×2

swift ×2