gpt4 book ai didi

ios - 如何在没有枚举的情况下更新swift3中字典数组中所有对象的键值?

转载 作者:行者123 更新时间:2023-11-29 11:49:13 26 4
gpt4 key购买 nike

如何在swift3中不枚举更新字典数组中所有对象的键值?

例如

let tags = [Dict("key1":true, "key2":1),Dict("key1":true,
"key2":2),Dict("key1":false, "key2":3),Dict("key1":true, "key2":1),
Dict("key1": false, "key2":1)]

现在我想为所有 Dict 对象更改值 if "key1":false

即我需要这样的输出

tag : [Dict("key1": false, "key2":1),Dict("key1": false,
"key2":2),Dict("key1":false, "key2":3),Dict("key1": false, "key2":1),
Dict("key1": false, "key2":1)]

我可以不用枚举或迭代来实现吗?以及如何?

最佳答案

你可以使用map函数:

let tags = [
["key1": true, "key2": 1],
["key1": true, "key2": 2],
["key1": false, "key2": 3],
["key1": true, "key2": 1],
["key1": false, "key2": 1]]

let newTags = tags.map { (dict) -> [String : Any] in
// dict is immutable, so you need a mutable shadow copy:
var dict = dict

dict["key1"] = false
return dict
}

正如 Paulw11 所提到的,此函数仍在隐式迭代。在一般情况下,如果您需要更新所有条目,您必须迭代这些条目。

根据您的数据,您可以使用引用类型对要更新的值进行建模。这可能有利于大型数据集,其中大量已知数据组共享相同的状态。

关于ios - 如何在没有枚举的情况下更新swift3中字典数组中所有对象的键值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41974752/

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