Chris
Chris

Reputation: 312

Add New Key/Value to Dictionary

I have a dictionary of type [String: [String]] and is loaded as blank [ : ].

Is there a way I can append a value to the array associated to a new string key? (i.e. exampleDict["test"].append("test"))

When I print out the dictionary after attempting this, I am returned [ : ], which I believe is because the key does not exist and returns as nil.

Upvotes: 0

Views: 243

Answers (2)

Charles Srstka
Charles Srstka

Reputation: 17060

Swift has a neat "default" feature for doing things exactly like this.

exampleDict["test", default: []].append("test")

If exampleDict["test"] is nil, the default is returned instead. If you modify the returned default object, that modification goes into the dictionary.

Unfortunately this only works properly for value types, since classes aren't reassigned when they're mutated. Fortunately, Array is a value type, so this will work perfectly here.

Upvotes: 2

Alexander
Alexander

Reputation: 63321

You have to use Dictionary.subscript(_:default:).

exampleDict["test", default: []].append("test")

Upvotes: 1

Related Questions