Kamil
Kamil

Reputation: 11

Swift How to access specific variable in a dictionary of Struct objects

A newbie in Swift here,

I have a Meal struct and I also have an array of Meal struct objects. Since Firestore doesn't have group-by option built in, I attempted to group the Meal array that I fetched from Firestore using Dictionary(grouping: ) initializer. I grouped the Meals by date of consumption, so I could then count the calories for a specific day.

Here's a snippet of my dictionary so far, I skipped some unnecessary fields:

["28 November 2021": [HealthyChoices.Meal(id: "...", calories_eaten: 40, meal_products: ["..."], date: "28 November 2021", who_ate: "..."), HealthyChoices.Meal(id: "...", calories_eaten: 50, meal_products: ["..."], date: "28 November 2021", who_ate: "...")]

As you can see, the key is the date by which the meals were grouped, and the value is the whole object fetched from Firestore. There can be of course many meals assigned to one date. Now what I want to do is to calculate the total calories eaten for a given day (key in this dictionary). Unfortunately I have no bloody idea what would be the way to iterate through this to get only this one specific field from every Meal (the "calories_eaten" field) and then count it for every date (the key in this dictionary).

I was trying to accomplish something with the map function but unfortunately seems I still cannot access the fields. I was trying something like this:

for (key, value) in groupedMeals {
     for key in groupedMeals.keys {
            value.get //no idea how to access that
     }
}

Please help, I give cookies.

Upvotes: 0

Views: 89

Answers (1)

SwiftSharp
SwiftSharp

Reputation: 91

You can use .mapValues on the dictionary:

var caloriesPerDay: Dictionary<String, Int> = groupedMeals.mapValues { meals in
    meals.map { meal in
        meal.calories_eaten // Get calories_eaten from each meal
    }.reduce(0, +) // Sum of the resulting [Int]
}

Upvotes: 1

Related Questions