在
Swift中,我想创建一个字典数组(具有多个键值对),然后迭代每个元素
以下是可能字典的预期输出.不知道如何声明和初始化它(有点类似于Ruby中的哈希数组)
dictionary = [{id: 1,name: "Apple",category: "Fruit"},{id: 2,name: "Bee",category: "Insect"}]
var airports: [String: String] = ["YYZ": "Toronto Pearson","dub": "dublin"]
解决方法
声明一个字典数组,使用这个:
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]]