Swift:初始化一个字典数组,其中键是一个String,value是一个类型

时间:2021-08-09 21:45:33

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)]

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" : []]

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

each time I try I get errors. any solutions?

每次我尝试我都会收到错误。任何解决方案

1 个解决方案

#1


1  

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:

您无法使用数组初始化元组值,因为它们是两种不同的类型。元组是一种独特的类型,必须包含您为其指定的元素数量。因此,如果您将字典声明为存储2元素元组,则必须使用两个元素存储其中的内容。因此,您可以使用以下内容初始化字典:

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]]

#1


1  

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:

您无法使用数组初始化元组值,因为它们是两种不同的类型。元组是一种独特的类型,必须包含您为其指定的元素数量。因此,如果您将字典声明为存储2元素元组,则必须使用两个元素存储其中的内容。因此,您可以使用以下内容初始化字典:

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]]