Reputation: 1220
I have dictionary like this
var dict : [String : Array<String>] = ["Fruits" : ["Mango", "Apple", "Banana"],"Flowers" : ["Rose", "Lotus","Jasmine"],"Vegetables" : ["Tomato", "Potato","Chilli"]]
I want to get values in array for each key How to get it in swift?
Upvotes: 0
Views: 22154
Reputation: 52237
2½ years and no-one mentioned map
?
ok, set aside that Dictionary
has a property values
(as ameenihad shows) which will do what you asking for, you could do:
let values = dict.map { $0.value }
Upvotes: 21
Reputation: 2126
EDIT: Try Something like this,
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)")
Above is how to get values of dictionay in swift, If you want to get contatenated array of all the values of dictionary(*only values), Try something like below.
print("values array : \(dict.map{$0.value}.flatMap{$0})")
values array : ["Rose", "Lotus", "Jasmine", "Tomato", "Potato", "Chilli", "Mango", "Apple", "Banana"]
Upvotes: -4
Reputation: 1870
Try:
var a:Array = dict["Fruits"]! ;
println(a[0])//mango
println(a[1])//apple
Upvotes: 1
Reputation: 1497
Try to get values as like following code
let fruits = dict["Fruits"]
let flowers = dict["Flowers"]
let vegetables = dict["Vegetables"]
Upvotes: 1
Reputation: 2459
try this:
for (key, value) in dict {
println("key=\(key), value=\(value)")
}
Upvotes: 2