在Swift 3上合并/附加[AnyHashable:Any]()

时间:2017-05-31 21:00:17

标签: swift

我有跟随对象,想要合并。

  var prop1 = [AnyHashable: Any]()
  prop1["key1"] = "Phase3"
  prop1["key2"] = "405"

  var prop2 = [AnyHashable: Any]()
  prop2["key3"] = "Phase1"
  prop2["key4"] = "45"

我想要一个最终对象prop1+prop2[AnyHashable: Any](),最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

你可以写

let union = Array(prop2.keys).reduce(prop1) { (dict, key) -> [AnyHashable:Any] in
    var dict = dict
    dict[key] = prop2[key]
    return dict
}

实施例

var prop1 = [AnyHashable: Any]()
prop1["key1"] = "Phase3"
prop1["key2"] = "405"

var prop2 = [AnyHashable: Any]()
prop2["key3"] = "Phase1"
prop2["key4"] = "45"


let union = Array(prop2.keys).reduce(prop1) { (dict, key) -> [AnyHashable:Any] in
    var dict = dict
    dict[key] = prop2[key]
    return dict
}

dump(union) // 

重复

请注意,如果两个词典中都存在相同的键,则结果将从prop2获取该特定键的值。

实施例

let prop1 : [AnyHashable: Any] = ["key1": "value from prop1"]
let prop2 : [AnyHashable: Any] = ["key1": "value from prop2"]


let union = Array(prop2.keys).reduce(prop1) { (dict, key) -> [AnyHashable:Any] in
    var dict = dict
    dict[key] = prop2[key]
    return dict
}

print(union) // [AnyHashable("key1"): "value from prop2"]