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) Data Modeling With Structures Swift Initializers

if (error == nil) ? why do we need this statement?

Why do we need to state if (error == nil)?

I know it relates to the NSerror in the completion handler but i don't fully understand what a completion handler goal is. I don't grasp the idea behind that could somebody explain to me

1 Answer

Nick Jones
Nick Jones
2,086 Points

A completion handler is, as the name would suggest, a block of code that should be run only when the function that the block is a part of is complete. Different completion handlers will return different parameters but one of them in your scenario is 'error'. The parameters that are returned but the completion handler don't have to be used and as per your example you could just not use the error variable at all. In the case of networking in particular however you will always want to handle your errors in some way as not doing so means that should anything go wrong (Which with mobile networks is more common than we'd like) your app is likely to simply crash. The code you've mentioned is simply a check to say "If everything has gone fine and we don't have any errors, then do this...". There may not be an 'else' clause included in the code at the moment to handle the scenario of "Oh something has gone wrong" and if this is the case that would be a great way to expand your current app yourself by handling the error gracefully.

I hope this helps but if not or if you need any extra information just let me know!