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 Interacting with Data From the Web Constructing a URL

Kevin Gonzales
Kevin Gonzales
4,638 Points

Why did we move the base URL?

The video said we moved it since the class forecastAPIKey had not yet been initialized. And I know he is right since we got errors, but I thought forecastAPIKey was a constant not a class. And I thought the code private let forecastAPIKey = "8768969698656" did initialize the constant forecastAPIKey since there is an = sign.

So what did I misunderstand? why can we not use forecastAPIKey except in the on create method ?

1 Answer

I believe this is because theforecastAPIKey is an instance property. It only gets initialized, either by it's automatic default initializer or by an init method setting it when the class is instantiated. This means the forecastAPIKey doesn't actually hold a value yet, so you cannot use it to define the baseURL's default value. I am just starting learning Swift, so this is my best understanding of it from reading Apple's documentation on properties[1]. From reading that I believe Swift now supports static properties in a class so you could do:

private static let theforecastAPIKey = "apiKey"
private static let baseURL = NSURL(string: "https://api.forecase.io/forecast/\(theforecastAPIKey)")

My guess is that at the time of this video Swift didn't support static stored type property values for classes, or they just didn't want to go into static properties just yet.

[1] https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html#//apple_ref/doc/uid/TP40014097-CH14-XID_369

Kevin Gonzales
Kevin Gonzales
4,638 Points

Thanks! The answer makes sense, but how is forecastAPIKey a instance property?

forecastAPIKey is an instance property because you aren't giving it the syntax of defining it as a type property. e.g. you aren't telling the class that this is a static property. In the link I provided above, search for "Type Properties" and read that section. It tells you the syntax, and the difference between the more common "instance properties", and these "type properties"