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 trialjames bunn
2,377 PointsClosure as a function parameter
In the video, Pasan mentioned the function getRecentBlogPosts has two closures.
First, the "completion" parameter of the function getRecentBlogPosts is a closure Next, the second parameter of the downloadTaskWithRequest method is a closure.
I understand how the second parameter of the downloadTaskWithRequest method is a closure because it follows the syntax mentioned in the prior videos. However, I don't understand how (completion: NSURLResponse! -> Void)) is a closure.
func getRecentBlogPosts (completion: (NSURLResponse! -> Void))
{
let treehouseDownloadTask = session.downloadTaskWithRequest(request)
{ (let url, let response, let eror) in }
2 Answers
Andrew Taylor
11,500 PointsI am guessing from looking at the code NSURLRepsonse returns void if it is not passed anything (null) and is therefore a closure.
Andrew Taylor
11,500 PointsThe variable "completion" I guess is doing that. Although it is a parameter, it is essential a variable expect you will initialize it when you call the function.
james bunn
2,377 PointsRight, so what variable is "completion" variable capturing that is outside its original scope? I assume it's the "response" object. I just don't understand how the "response" object is outside the original scope
james bunn
2,377 Pointsjames bunn
2,377 PointsI thought in order to be a closure, you have to capture variables which are outside the original scope. Which variables is "completion" capturing?