2014-12-11 38 views
-4

我的字典是这样如何获得字典的值在数组中迅速

var dict : [String : Array<String>] = ["Fruits" : ["Mango", "Apple", "Banana"],"Flowers" : ["Rose", "Lotus","Jasmine"],"Vegetables" : ["Tomato", "Potato","Chilli"]] 

我想值阵列的每个关键如何得到它迅速?

回答

-4

编辑: 尝试这样的事情,

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

以上是如何。如果你想获得 词典(所有值contatenated阵列得到百科的价值在迅速, *只值), 尝试下面的内容。

print("values array : \(dict.map{$0.value}.flatMap{$0})") 

值数组:[ “玫瑰”, “莲花”, “茉莉花”, “番茄”, “土豆”, “辣椒”, “芒果”, “苹果”, “香蕉” ]

0

尝试:

var a:Array = dict["Fruits"]! ; 

println(a[0])//mango 

println(a[1])//apple 
0

试试这个:

for (key, value) in dict { 
    println("key=\(key), value=\(value)") 
} 
0

尝试获得价值像下面的代码

let fruits = dict["Fruits"] 
let flowers = dict["Flowers"] 
let vegetables = dict["Vegetables"] 
0
for val in dict.values { 
    print("Value -> \(val)") 
} 
3

两年半的时间,没有人提到map

OK,抛开那Dictionary有一个方法values,将你问什么,你可以这样做:

let values = dict.map { $0.value }