我有这样的字典
var dict : [String : Array<String>] = ["Fruits" : ["Mango", "Apple", "Banana"],"Flowers" : ["Rose", "Lotus","Jasmine"],"Vegetables" : ["Tomato", "Potato","Chilli"]]
我想为每个键获取数组中的值如何在swift中获取它?
编辑:尝试这样的事情,
var dict : [String : Array<String>] = [
"Fruits" : ["Mango", "Apple", "Banana"],
"Flowers" : ["Rose", "Lotus","Jasmine"],
"Vegetables" : ["Tomato", "Potato","Chilli"]
]
var myArray : Array<String> = []
// You can access the dictionary(dict) by the keys(Flowers, Flowers, Vegetables)
// Here I'm appending the array(myArray), by the accessed values.
myArray += dict["Fruits"]!
myArray += dict["Vegetables"]!
print("myArray \(myArray)")
上面是如何在swift中获取字典的值,如果你想得到字典的所有值的连接数组(*只有值),尝试类似下面的内容。
print("values array : \(dict.map{$0.value}.flatMap{$0})")
值数组:[“玫瑰”,“莲花”,“茉莉花”,“番茄”,“马铃薯”,“辣椒”,“芒果”,“苹果”,“香蕉”]
试试这个:
for (key, value) in dict {
println("key=\(key), value=\(value)")
}
尝试获取值如下面的代码
let fruits = dict["Fruits"]
let flowers = dict["Flowers"]
let vegetables = dict["Vegetables"]
尝试:
var a:Array = dict["Fruits"]! ;
println(a[0])//mango
println(a[1])//apple
for val in dict.values {
print("Value -> \(val)")
}