简体   繁体   中英

How to update value of a key of all objects from array of dictionary in swift3 without enumeration?

How to update the value of a key of all objects from an array of a dictionary in swift3 without enumeration?

Eg

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

Now I want to change the value if "key1":false for all Dict objects.

ie I need output like this

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

Can I achieve this without enumeration or iterations? and How?

You can use the map function:

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
}

This function is implicitly still iterating as mentioned by Paulw11. In the general case you have to iterate over the entries if you need to update them all.

Depending on your data you may be able to model the value to be updated with reference types. This could be beneficial for huge datasets where large known groups of data share the same state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM