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 Managing Complexity Network Operations

Mathis ClaรŸen
Mathis ClaรŸen
4,892 Points

self.

Why does the keyword self. fix the problem with the lazy loaded config var?

Why is it : self.queryURL = url instead of: queryURL = url in the init method?

Kevin Gonzales
Kevin Gonzales
4,638 Points

The answer given was that since we are lazy loading (not initializing until we need the vars) the compiler doesn't know what configuration we are referring to. I don't really understand completely either, but my best guess is that since the vars have not been initialized the var used needs to be more specific therefore it uses self.? i am not sure why but I hoped this helps, and hope someone can explain better since I am curious too.

1 Answer

I think it's because Swift doesn't know if it's referring to an instance property or a 'static' property unless you include self.config. Static properties are stored against actual classes instead of an instance, so that all instances share the same property of it's class.

I've answered this in more detail in another question here https://teamtreehouse.com/forum/what-is-the-reason-for-selfconfig but basically you could rewrite your code like so...

class NetworkOperation {
    static var config: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
    var session: NSURLSession = NSURLSession(configuration: config)

...but all NetworkOperation instances will share the same NSURLSessionConfiguration instance.

Regarding self.queryURL = url vs queryURL = url in the init() method, it doesn't actually matter. But some people prefer to write self.propName (including myself) because it makes it more explicit/readable regarding what you're doing.