1

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 ?

1
  • TabActions should be tabActions - instances lower case - Classes/Struc Definition upper case Commented Jun 22, 2017 at 21:57

2 Answers 2

2

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"
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. In your second proposition (without the Array) how to do if the first key (EVENT1) does not exist if I want the creation of both the key and the nested dictionary elements ("TARGET3", "ACTION3") associated to this key ?
Good point, you need to check if there is an existing dictionary for a given key: if let targets = TabActions["EVENT2"] { TabActions["EVENT2"]?["TARGET3"] = "ACTION3" } else { TabActions["EVENT2"] = ["TARGET3" : "ACTION3" ] }
0

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.

1 Comment

Thanks for this quick answer ! What would I do in the case the first key does not exist as the append won't do anything as you said ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.