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 trialPaul Je
4,435 PointsQuestion about Closures
I'm pretty confused about Closures as a whole. So is a correct simplification that, if you refer to a constant using a function, which is to return a value regardless of when, you can call it back from another constant later on only when it's ready by possibly integrating an optional? Maybe a potential use of this it that the app or program should only run in procedure A only if the callback returns a non-nil value, but otherwise run in procedure B? Hope that made sense.. any help would be appreciated,
1 Answer
Harish Yerra
10,031 PointsWell, what a closure is designed to do is provide data that isn't available instantly. So let's take a possible scenario ->
I have an app and I need it to connect to the internet to provide me with some data that my app can use. The data won't be available instantly.
In your question you asked if you can call back later by integrating an optional but that wouldn't be the best because you wouldn't know when your closure is finished executing. The best way to do this would be with a completion handler. A completion handler waits for the closure to finish executing and does something with that data once it's done (possibly calling another function, updating UI, etc).
So basically a closure is just a way of getting data that is fetched asynchronously. You query data in the background, and then once that data is called your completion handler is triggered and you can respond appropriately with the new data.