Jonah Begood
Jonah Begood

Reputation: 317

swift add element in a array of dictionary nested in a dictionary

I have the following code :

var TabActions: Dictionary<String, Array<Dictionary<String, String>>> = [:]

TabActions = ["EVENT1" : ["TARGET1" : "ACTION1"], ["TARGET2" : "ACTION2"]]

I want to add ["TARGET3" : "ACTION3"] to the list but I can't figure how to do this. I've tried :

TabActions["EVENT1"] = [["TARGET3" : "ACTION3"]]

but it replaces the value instead of adding it and all other attempts end up with an error

What would be the best syntax to do this ?

Upvotes: 1

Views: 3882

Answers (2)

Sergio G
Sergio G

Reputation: 36

If you do really need a dictionary of arrays of dictionaries as presented, then Antonio's answer is correct, append will do the job:

var TabActions: Dictionary<String, Array<Dictionary<String, String>>> = [:]
TabActions = ["EVENT1" : [["TARGET1" : "ACTION1"], ["TARGET2" : "ACTION2"]]]

TabActions["EVENT1"]?.append(["TARGET3" : "ACTION3"])

On the other hand if you can get by with a simpler dictionary of dictionaries you just need to do:

var TabActions: Dictionary<String, Dictionary<String, String>> = [:]       
TabActions = ["EVENT1" : ["TARGET1" : "ACTION1", "TARGET2" : "ACTION2"]]

TabActions["EVENT1"]?["TARGET3"] = "ACTION3"

Upvotes: 2

Antonio
Antonio

Reputation: 72760

The TabActions dictionary contains array values - and to append to an array you use the append method:

TabActions["EVENT1"]?.append(["TARGET3": "ACTION3"])

Note that if the EVENT1 key is not found, no addition takes place.

Upvotes: 0

Related Questions