Bigbigga
Bigbigga

Reputation: 37

Combine two arrays to one dictionary in Swift

I have two array given:

let data = ["12 Mai 2021", "12 Mai 2021"]
let prices = [45.0, 50.0]

now I would like to transform these two into one Dictionary like this:

["12 Mai 2021":45.0, "12 Mai 2021":50.0]

It would be even better if the output could be:

[("12 Mai 2021",45.0),("12 Mai 2021",50.0)]

But I don't know if thats possible.... On this board I already stumbled across the "zip" solution, like this:

var dictionary = [String: Double]()
zip(data, prices).forEach { dictionary[$0] = $1 }
print(dictionary)

But this somehow just prints:

["12 Mai 2021": 50.0]

Someone knows a working solution? Thank you in advance!

Upvotes: 1

Views: 1283

Answers (1)

rob mayoff
rob mayoff

Reputation: 385690

You say you want this Dictionary:

["12 Mai 2021":45.0, "12 Mai 2021":50.0]

But that is impossible. Each key in a Dictionary must be unique. The key "12 Mai 2021" cannot be used twice.

Then you say you would prefer this “output”:

[("12 Mai 2021",45.0),("12 Mai 2021",50.0)]

That is an array of pairs (2-tuples), and you can get that answer using zip:

let pairs = zip(data, prices).map { $0 }
// Type of pairs is [(String, Double)].

If you really want a Dictionary, then you have to decide what to do about duplicate keys. Maybe you want each date key to map to an array of the prices for that date. Here's one way to do that:

let d = Dictionary(zip(data, prices.map { [$0] })) { $0 + $1 }
// Result: ["12 Mai 2021": [45.0, 50.0]]

Here's what the code above does.

  1. prices.map { [$0] } transforms prices from [Double] to [[Double]], that is, into an array of arrays of Double, where each inner array contains just one price: [[45.0], [50.0]].

  2. zip combines the dates and the single-price arrays into pairs: [("12 Mai 2021", [45.0]), ("12 Mai 2021", [50.0])].

  3. The Dictionary initializer converts the array of pairs into a [String: [Double]]. When it finds duplicate keys, it combines the corresponding values using the closure { $0 + $1 }. Here, $0 and $1 are each a [Double], so the closure joins the arrays.

Upvotes: 2

Related Questions