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 Downloading JSON Data Asynchronously Returning JSON

Bastian Petersson
Bastian Petersson
9,164 Points

why @escaping closure?

I don't understand why it needs to be an @escaping closure? Can someone try and explain it to me and maybe give an example?

Thanks

1 Answer

Caleb Kleveter
MOD
Caleb Kleveter
Treehouse Moderator 37,862 Points

I wold recommend reading this section of the Swift blog post on closures.

The important part is this paragraph:

A closure is said to escape a function when the closure is passed as an argument to the function, but is called after the function returns. When you declare a function that takes a closure as one of its parameters, you can write @escaping before the parameter’s type to indicate that the closure is allowed to escape.

So, in the code that Pasan is writing in the video, the closure is escaping because it is called in the callback of the data task. The data task is being returned from the method, but since the task has not been run yet, the data task's callback, and thus the closure, has not been called yet. It will be called after the method returns.

Hope that explains it for you!

Bastian Petersson
Bastian Petersson
9,164 Points

Thank you. I think I have a better understanding of it now