我有跟随对象,想要合并。
var prop1 = [AnyHashable: Any]()
prop1["key1"] = "Phase3"
prop1["key2"] = "405"
var prop2 = [AnyHashable: Any]()
prop2["key3"] = "Phase1"
prop2["key4"] = "45"
我想要一个最终对象prop1+prop2
和[AnyHashable: Any]()
,最好的方法是什么?
答案 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"]