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 trialSheep McSheep
846 PointsCompletion handler syntax
let dataTask = session.dataTaskWithRequest(request) {
(let data, let response, let error) in
}
In the dataTaskWithRequest completion handler closure, what is the purpose of "let" in front of data, response, and error parameters? Removing it doesn't seem to cause any errors.
2 Answers
Dominic Bryan
14,452 PointsWithout typing a HUGE answer, you are correct it makes no difference to the interpreter. However ironically enough the "let" is purely readability in this case.
Because the completionHandler creates url, response and error, they could be variables or constants. Pasan simply specified them to be constants, its honestly more for readability I believe and not overwriting the previous url constant declared in the global scope (They will be the same value but different in their respective scopes).
Rafael Nicoleti
87 PointsThis solution it's work
func downloadJSONFromURL(completion: JSONDictionaryCompletion) {
let request = NSURLRequest(URL: queryURL)
let task = session.dataTaskWithRequest(request) {
(data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
if error != nil {
completion(nil)
}
if let data = data {
do
{
let object = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as! [String: AnyObject]
completion(object)
} catch {
completion(nil)
}
} else {
completion(nil)
}
}
task?.resume()
}
Dominic Bryan
14,452 PointsThis is a working piece of code, but I think there is slight confusion around your answer and the question asked. Sheep McSheep wanted to understand why the parameters in the completion had "let" (constant) called in front of them.
But keep it up man, its good to try answer peoples questions on the forum.
Sheep McSheep
846 PointsSheep McSheep
846 PointsThanks! Just trying to get a handle on the fifty million different ways swift closures can be written.