Swift Function Syntax Breakdown

I apologize in advance for the title of this question.

I’m hoping to get a breakdown on some syntax elements of a function in Swift.

The function:

let call:NSURLSessionDataTask = session.dataTaskWithRequest(request) {
    data, response, error in

    if error != nil {
        println("error=(error)")
        return
    }

    println("response = (response)")
}

What I’m wondering is line by line, how do the elements effect the constant?

What I see;

1) A constant being set to be the result of a function (session.dataTaskWithR...) with a “request” parameter followed by what seems to be the beginning of a closure function { to execute when triggered. (with call.resume())

2) Are these declared variables for the function? Are they being assigned here? Seems weird to just write “data,response,error” at the top of a function or object, I assume/know these are populated with data returned from the session.dataTas.. call. It just seems as though they are undeclared and not typed.

4) This seems pretty straight forward that if error is not nil, print the error and exit.

9) print the response headers.

So, I guess my main question is regarding line 2. I see no meaning to just writing variable names other than, that’s just how it is done. Is this just how it’s done?


Source: syntax

Leave a Reply