General question about declaring variables

I’m just a few weeks in to my learning and am almost done the card matching game. One part that continues to give me some confusion when I go back to recreate the code on my own, is I’m often unsure whether to declare the variables at the top of the view controller class, or within individual functions. I’m thinking along the lines that if it’s only used in the function, then it gets declared in the function only? is that right? I thin that might be the source of my confusion, maybe I just don’t have it visualized in my head well enough yet how broadly a particular variable will be needed.

Declare your variables where they will be used. If the same variable (not the same name but the actual variable) is used in multiple places within your class, then declare it at the top level of the class. If it’s only used within one function, declare it in that function.

1 Like