Write to Nested Dictionary (Swift 4)

Viewed 382

I have declared a dictionary in Swift as so: var dict = [String: [String: [String]]]().

What I am trying to do now is to write to the nested dictionary. I have used both codes below, however, none of them work as the initial key does not exist:

dict["Test"]?["One"] = ["Failed"]
dict["Test"]!["One"] = ["Failed"]

What I am trying to do is to create a key for ["One"], much like how you can create a key for a normal dictionary using dict[key].

2 Answers

You need to instantiate every inner dictionary.

var dict = [String : [String : [String]]]()

dict["Test"] = [String : [String]]()

dict["Test"]?["One"] = ["Worked"]

print(dict)

Make sure to avoid force unwrapping.

dict is empty. There is no value for the "Test" key.

One option is to provide a default:

dict["Test", default: [:]]["One"] = ["A", "B"]

You can take this one step further:

dict["Test2", default: [:]]["Two", default: []].append("Hello")

That last line will work for any combination of the keys "Test2" and "Two" existing or not before that is used.

Related