Reputation: 135
I made a dictionary.
let fruits = ["aa":"apple", "bb":"banana", "gg":"grapes" ]
and I have a array which contains same keys of 'fruits'
let fruitsKeys = ["aa", "bb", "gg"]
and I want to get the array of 'fruits' values by inspecting Dictionary 'fruits' one by one using elements in Array 'fruitsKey'.
This array will looks like
fruitsValue = ["apple", "banana", "grapes"]
How can I get the value for 'keys in an array' in Dictionary?
Upvotes: 0
Views: 488
Reputation: 154603
To get the array of corresponding values for the array of key values, use compactMap
to create the array:
let fruits = ["aa":"apple", "bb":"banana", "gg":"grapes" ]
let fruitsKeys = ["aa", "bb", "gg"]
let fruitsValue = fruitsKeys.compactMap { fruits[$0] }
print(fruitsValue)
["apple", "banana", "grapes"]
Notes:
nil
and compactMap
will leave it out.Upvotes: 2
Reputation: 21
In this scenario, if you just want all the fruit values, you don't need to search by iterating over fruitsKeys
. Just iterate through all the values like so:
for fruit in fruits {
fruitsValue.append(fruit.value)
}
If you need to fetch the values based on the available keys in fruitsKeys
, the iteration could be like this:
for fruit in fruits {
if fruitsKeys.contains(fruit.key) {
fruitsValue.append(fruit.value)
}
}
Upvotes: 0