gpt4 book ai didi

swift - 合并/追加 [AnyHashable : Any]() on Swift 3

转载 作者:行者123 更新时间:2023-11-28 06:18:51 25 4
gpt4 key购买 nike

我有以下对象,然后想合并。

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

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

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

最佳答案

你可以写

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"]

关于swift - 合并/追加 [AnyHashable : Any]() on Swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44294588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com