Rogue
Rogue

Reputation: 779

Appending to an Array of Dictionaries in Swift

I'm building a complex structure. It's a Dictionary indexed by String, that contains an array of [String: String] dictionaries:

var t: [String: [[String: String]]] = [:]

My problem is: when I try to append values to the list, by doing the following:

t["key1"].append([val1: ..., val2: ..., ...])

I get this error: Cannot invoke method 'append' with an argument list of type [String: String]

Is there a way to fix this? I tried initialising the t["key1"] list, by doing t["key1"] = []. This didn't help.

Thanks a lot.

Upvotes: 1

Views: 48

Answers (2)

ridvankucuk
ridvankucuk

Reputation: 2407

Your t value is a dictionary and you are trying to append it. You can do it like this:

t["key1"] = []
t["key1"]?.append(["a":"b"])
t["key1"]?.append(["c":"d"])

Upvotes: 2

Aderstedt
Aderstedt

Reputation: 6518

Try it like this:

var t : [String: [ [ String: String] ] ] = [:]

t["key1"] = []
t["key1"]!.append(["a key":"a value"])

Upvotes: 2

Related Questions