简体   繁体   中英

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 ?

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"

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.

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