0

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?

6 Answers 6

21

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 }
Sign up to request clarification or add additional context in comments.

Comments

2

try this:

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

Comments

1

Try to get values as like following code

let fruits = dict["Fruits"]
let flowers = dict["Flowers"]
let vegetables = dict["Vegetables"]

Comments

1

Try:

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

println(a[0])//mango

println(a[1])//apple

Comments

1
for val in dict.values {
    print("Value -> \(val)")
}

Comments

-4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.