在Swift中我想创建一个字典数组(具有多个键值对),然后迭代每个元素
以下是可能字典的预期输出。不知道如何声明和初始化它(有点类似于Ruby中的哈希数组)
dictionary = [{id: 1, name: "Apple", category: "Fruit"}, {id: 2, name: "Bee", category: "Insect"}]
我知道如何用一个键值对创建一个字典数组。 例如:
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
答案 0 :(得分: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]]
答案 1 :(得分: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)
}
导致
["一个":1,"两个":2]
[" b":2," a":1]
答案 2 :(得分:1)
let airports: [[String: String]] = [["YYZ": "Toronto Pearson", "DUB": "Dublin"]]
for airport in airports {
print(airport["YYZ"])
}