如何组合两个复杂的词典

时间:2016-08-11 18:16:58

标签: ios swift

我很好奇如何组合两个字典,其中一个包含键与数组或另一个字典作为值。

用于简单组合,例如

    var dict1 = ["bbb":"dict1",
                 "her": "dict1"]

    let dict2 = ["aaa":"dict2",
                 "her": "doct2",
                 "bob": "doct2"]

    dict1 += dict2 // result is as I expected


    func += <K, V> (inout left: [K:V], right: [K:V]) {
        for (k, v) in right {
            left.updateValue(v, forKey: k)
        }
    }

但是当我想要组合更复杂的词典时,问题就会出现,例如。

var dict1 = ["bbb":"dict1",
             "her": "dict1"]


let complexDict2 = ["aaa":"dict2",
                    "her": "dict2",
                    "arr": ["one", "two"]]


dict1 += complexDict2 // in here method which override '+=' operator for dictionaries does not work anymore...

我的问题是你们是否有一种经过验证的方法来组合更复杂的词典?

Upadate

组合dict1和complexDict2的预期结果是:

let resultDict    = ["aaa":"dict1",
                    "aaa":"dict2",
                    "her": "dict2",
                    "arr": ["one", "two"]]

1 个答案:

答案 0 :(得分:2)

此处的问题在于dict1complexDict2

的类型

dict1被推断为类型为[String : String],而complexDict2被推断为类型为[String : Any]

如果您在dict1上明确指定了类型注释:

,那么您的代码可以正常运行
var dict1: [String : Any] = [
    "aaa":"dict1",
    "her": "dict1"
]