Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Build a Weather App with Swift (Retired) Pulling Data From the Web Networking in iOS

Why does Pasan define the forecastURL constant within the viewDidLoad function rather than outside of it?

Can someone explain the difference between defining constants and variables within and outside of the viewDidLoad function? I don't quite understand the concept and am wondering how I would know to do this when developing an app on my own.

2 Answers

Pasan Premaratne
STAFF
Pasan Premaratne
Treehouse Teacher

Aaron Williamson

Defining the forecastURL outside viewDidLoad() would've meant creating a stored property as Stone mentions. When defining variables or constants that refer to other properties (in this case the API key) we access these properties through they keyword self. Self doesn't need to be explicitly declared but thats what is being done in the back anyway.

For self to be accessed the class and any base/super classes need to be initialized. This would have meant creating an initializer method for the view controller and there's some setup that goes into it that would have made the video longer and convoluted so I opted to put it inside the viewDidLoad method instead.

You can certainly do it outside the viewDidLoad and in an init method if you chose.

Stone Preston
Stone Preston
42,016 Points

declaring variables/constants inside a function means that variable/constant has local scope relative to the function its declared in. In other words, it is only accessible from within that single function.

declaring a variable/constant outside any function but inside a class means that variable/constant is a property and is available throughout the class

Thanks for your answer Stone. I understand the concept of scope pretty well, but why does it matter in this case? What is special about the viewDidLoad function that prompted Pasan to put the constant inside of it? Does that mean whenever we use API keys we should put them in this function? I'm just curious why he chose to scope the API key, and why he chose the viewDidLoad function in particular to do it.