UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Trouble with creating a loop that increments a value.

Forums > Swift

@Jawds  

Hi,

I am making an app that stores a user's food items throughout the day, as well as letting them enter the calories for each specific food item.

I am using a ForEach to add them all to a singular var which will then be displayed in the user interface.

Let me know if any context for the code is needed.

var calorieAmount: Int {
        let calendar = Calendar.current
        let day = calendar.component(.day, from: entrydate)
        var calorieTotal = 0

        ForEach(foods, id: \.self) { food in
            if (food.date == day) {
                var calories: Int = Int(food.calories)
                calorieTotal += calories
            }
        }
        return calorieTotal
    }

This returns an error within ContentView (Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols).

I don't know whether this is due to me placing it in the wrong place, or just has to do with the structure of the code itself.

Thank you in advance.

2      

I assume this is inside the body property of a View? Yeah, you can't do that. Instead, you need to do something like this:

var calorieAmount: Int {
    let calendar = Calendar.current
    let day = calendar.component(.day, from: entrydate)
    var calorieTotal = 0

    for food in foods {
        if food.date == day {
            calorieTotal += food.calories
        }
    }

    return calorieTotal
}

Since this is not part of the body, you can't use ForEach and have to use a regular for loop.

This needs to be a computed variable in your ContentView struct but outside of the body property. So...

struct ContentView: View {
   let foods: [Food]

   var calorieAmount: Int {
       //... above code
   }

   var body: some View {
       //...your UI content, where at some poiunt you reference calorieAmount
   }
}

3      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.