Hoo
Hoo

Reputation: 135

How to get the value for 'keys in an array' in Dictionary in swift4

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

Answers (2)

vacawama
vacawama

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:

  1. The corresponding values will be in the same order as the keys in the original array.
  2. If a key doesn't actually have a value, this will safely skip that key because the lookup will return nil and compactMap will leave it out.

Upvotes: 2

Josh Austin
Josh Austin

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

Related Questions