Beezebrown
Beezebrown

Reputation: 45

Swift: Initializing an array of dictionaries, where the key is a String, and value is a type

I have an array which stores a dictionary. The dictionary has a String for a key, and a Tuple for the value. It looks like this:

var mydict: [String: (key1: String, key2: String)]

I want to initialize this array with a key, and an empty array for a value.

So like this:

var mydict: [String: (key1: String, key2: String)] = ["dict_key1" : []]

each time I try I get errors. any solutions?

Upvotes: 0

Views: 839

Answers (1)

Charles Srstka
Charles Srstka

Reputation: 17050

You can't initialize a tuple value with an array, because they're two different types. A tuple is a distinct type that has to contain the number of elements you specified for it to contain. So if you declare your dictionary as storing 2-element tuples, you have to store something in it with two elements. So you could initialize your dictionary with something like:

var mydict: [String: (key1: String, key2: String)] = ["dict_key1" : (key1: "", key2: "")]

However, if you want to store an array in the dictionary, I'd suggest you just type the dictionary as such:

var mydict: [String : [String]]

Upvotes: 1

Related Questions