Swift字典包含多个键值对 - 迭代

4

在Swift中,我想创建一个包含多个键值对的字典数组并遍历每个元素。

下面是可能的字典预期输出。不确定如何声明和初始化它(与Ruby中的哈希数组有些相似)。

 dictionary = [{id: 1, name: "Apple", category: "Fruit"}, {id: 2, name: "Bee", category: "Insect"}]

我知道如何制作一个只有一个键值对的字典数组。 例如:
 var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"] 

你的 airports 变量不是一个字典数组,而只是一个字典。但是如果你像这样声明它 var airports: [[String: String]] = [["YYZ": "Toronto Pearson", "DUB": "Dublin"]],它就会成为一个字典数组,只需要注意花括号即可。 - Dániel Nagy
3个回答

5

要声明一个字典数组,请使用以下代码:

var arrayOfDictionary: [[String : AnyObject]]  = [["id" :1, "name": "Apple", "category" : "Fruit"],["id" :2, "name": "Microsoft", "category" : "Juice"]]

我看到你的字典中混合了数字和字符串,因此最好使用AnyObject代替String作为字典中的数据类型。如果在此代码之后不必修改此数组的内容,请将其声明为'let',否则请使用'var'

更新:在循环中初始化:

//create empty array
var emptyArrayOfDictionary = [[String : AnyObject]]()
for x in 2...3 {  //... mean the loop includes last value => x = 2,3
    //add new dictionary for each loop
    emptyArrayOfDictionary.append(["number" : x , "square" : x*x ])
}
//your new array must contain: [["number": 2, "square": 4], ["number": 3, "square": 9]]

谢谢,这很有道理。如果我想在for循环中初始化,例如我想要:dictionary:[[String: AnyObject]] =[ ["number": 2, "square": 4],["number: 3, "square": 9]],该怎么做?下面的代码不起作用:var dictionary: [[String: AnyObject]]for x in 2...3 { var new = ["number" : x, "square": x*x] somehow append new to dictionary } - Anuj Arora

1
let dic_1: [String: Int] = ["one": 1, "two": 2]
let dic_2: [String: Int] = ["a": 1, "b": 2]
let list_1 = [dic_1, dic_2]

// or in one step:
let list_2: [[String: Int]] = [["one": 1, "two": 2], ["a": 1, "b": 2]]

for d in list_1 { // or list_2
    print(d)
}

这将会得到以下结果:

["one": 1, "two": 2]

["b": 2, "a": 1]


1
let airports: [[String: String]] = [["YYZ": "Toronto Pearson", "DUB": "Dublin"]]

for airport in airports {
    print(airport["YYZ"])
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接