Learn Courses My Dashboard

Where Do I have to make functions

One thing I could not understand is in order to make a function on an app, we make a method or “func,” but I don’t know where exactly we have to declare it or specify it in the ViewModel file or in the view itself.
I’m utterly confused.

Functions are declare with the func keyword, like you noted, and then the function name.

These can go in your view, OR in the view model, it all depends on what you’re trying to achieve.

When putting them in a SwiftUI view, you should put it below the body, but before the struct ends.

In a View model it can go pretty much anywhere.

Have you watched the beginner 14 day challenge?

Yes I understood it clearly when I was watching the beginner challenge. When I was trying to make other apps then I also had to pass the information on the function and I think for that I need to put them on a proper place. That’s what I don’t know

Like when I was watching the recipe app; I saw Chris created a func to calculate the recipe portion size . when I was doing the same and I created the func I was not able to pass the ingredients data on it.

In your version of the Recipe App is might be worth setting some breakpoints to see what is going on.

Hey @riskjockeyy , have a look at the code I wrote for the list challenge.

As you’ll see I created a function called ‘selectCard’. This function or method sits inside the Structure ‘ContentView’ at the top of the code. Within the ‘ContentView’ structure I call this method on line 39.

In short, functions sit inside structures. If you create an instance of this structure you can also call this method.