How can I convert 2 dictionaries into an array Objects?

I've been trying to accomplish this but I haven't been to able do so.


I have two dictionaries where certain values may be repeated it another dictionary (that is the key that represents that dictionary) for example:


var foodId_QtityDict = [String: Int]()
var productNamesDict = [String: String]()



dump from my 2 dictionaries which I filled from network data using Alamofire


▿ 2 key/value pairs

▿ [0]: (2 elements)

- .0: 6 < 6 is here

- .1: 1 < there is only 1 element of id 6

▿ [1]: (2 elements)

- .0: 5

- .1: 2 < there are 2 elements of id 5

---Second dictionary

▿ 2 key/value pairs

▿ [0]: (2 elements)

- .0: 6 < 6 is also here

- .1: Burrito

▿ [1]: (2 elements)

- .0: 5

- .1: Tacos

I want to do the following: use a struct or a class to create an array of objects based on those two dictionaries but I don't want to repeat the ID's ( number 6 and number 5 in this case)


For this example I should have an array of two objects


▿ [0]: TablePinAdolfoTesting.FoodItem #0

- id: 5

- name: Tacos

- quantity: 2

▿ [1]: TablePinAdolfoTesting.FoodItem #1

- id: 6

- name: Burritos

- quantity: 1

I decided to go this route because with a dictionary I can easily access the key that holds the quantity of one item. Hence, if an user wants to add another count of the same item to his cart, I can just add 1 to that dictionary. At first I was using the object directly as an item in my cart but then I would have repeated objects like so

[0]: TablePinAdolfoTesting.FoodItem #0

- id: 5

- name: Tacos

- quantity: 1

▿ [1]: TablePinAdolfoTesting.FoodItem #1

- id: 6

- name: Burritos

- quantity: 1

[2]: TablePinAdolfoTesting.FoodItem #2

- id: 5

- name: Tacos

- quantity: 1



Thank you very much, as a beginner in Swift this has proven to be challeging

I'm not sure if this really fulfills your app's requirements, but map(_:) of Dictionay can create an Array with each elements generated by key and value of the Dictionary.

let combinedArray = foodId_QtityDict.map {(id, quantity) in
    (id: id, name: productNamesDict[id] ?? "?", quantity: quantity)
}

The closure passed the `map` method is just converting the (id, quantity) tuple to (id, name, quantity) tuple using productNamesDict.

How can I convert 2 dictionaries into an array Objects?
 
 
Q