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

标签 ios swift3

如何在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/

相关文章:

ios - 如何以编程方式检查应用程序商店区域/国家?

html - iOS 10 : uncertain freezing during scroll of HTML list styled with -webkit-overflow-scrolling: touch

ios - watchOS 是否支持自定义 SiriKit Intents 的语音快捷方式?

ios - UIGraphicsGetImageFromCurrentImageContext() 返回 nil

IOS swift如何知道activityViewController何时被成功使用

ios - 在 iOS 上设置初始焦距

swift - 字符串到 C 字符** Swift 3

ios - 无法将此 JSON 转换为字符串

swift - 从 Swift 3 中的对象获取字符串

ios - Swift 3 照片拍摄