Kent Wong
Kent Wong

Reputation: 581

How to map an array of integers as keys to dictionary values

If I have the following array and I want to create a string array containing the door prizes by mapping the mysteryDoors array as keys for the dictionary, and get the corresponding values into a new array.

Thus I would get a string array of ["Gift Card", "Car", "Vacation"] how can I do that?

let mysteryDoors = [3,1,2]

let doorPrizes = [
    1:"Car", 2: "Vacation", 3: "Gift card"]

Upvotes: 1

Views: 562

Answers (3)

Kent Wong
Kent Wong

Reputation: 581

After re-reading the Apple Doc example code and changing it to what I need. I believe this is it (Almost). Unfortunately it is now in string format with new lines...

let myPrizes = doorPrizes.map { (number) -> String in
    var output = ""
    output = mysteryDoors[number]!
    return output;
}

Upvotes: 0

Martin R
Martin R

Reputation: 539775

You can map() each array element to the corresponding value in the dictionary. If it is guaranteed that all array elements are present as keys in the dictionary then you can do:

let mysteryDoors = [3, 1, 2]
let doorPrizes = [ 1:"Car", 2: "Vacation", 3: "Gift card"]

let prizes = mysteryDoors.map { doorPrizes[$0]! }
print(prizes) // ["Gift card", "Car", "Vacation"]

To avoid a runtime crash if a key is not present, use

let prizes = mysteryDoors.flatMap { doorPrizes[$0] }

to ignore unknown keys, or

let prizes = mysteryDoors.map { doorPrizes[$0] ?? "" }

to map unknown keys to a default string.

Upvotes: 2

sCha
sCha

Reputation: 1504

If you have to use map, then it would look something like the following:

let array = mysteryDoors.map { doorPrizes[$0] }

Upvotes: 1

Related Questions