Supriya Nale
Supriya Nale

Reputation: 49

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?

E.g

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.

i.e 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?

Upvotes: 1

Views: 1572

Answers (1)

nils
nils

Reputation: 1976

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.

Upvotes: 1

Related Questions