18

I found some code written in Swift on github,

And get a little confused about this line

var done: (NSError?, NSData, NSString?) -> () = { (_, _, _) -> () in } 

could you please explain the real meaning of this line? Thank you very much!

1
  • the line with in specifies the signature of the closure. It allows you to name the inputs parameters and also specify the output return type Commented Jun 17, 2014 at 18:22

3 Answers 3

15

_ means don't name that thing. It can be used in a number of places. In your case, it is saying ignore the variable being passed into the closure. The code you gave is ignoring all parameters but you can also just ignore some parameters.

in is the start of the implementation of the closure. In your example code, the implementation of the closure is empty.

Overall, that line is defining a closure called "done" that takes an Optional NSError (NSError?), NSData (NSData), and Optional NSString (NSString?) and returns nothing (-> ()). The actual implementation of the closure does nothing.

Sign up to request clarification or add additional context in comments.

5 Comments

Expanding on @drewag's answer a bit: "The actual implement does absolutely nothing"... because that closure is provided as a default value for the done property, and the user of this Request class is expected to provide a closure that actually does something. In that closure, you'd provide local names for the parameters instead of using _ (as seen on what's currently line 55 in that gist).
@rickster Thanks for all your fascinating answers! I have another question about this code in the gist. When will the function "connection" be called? I found that there are three function sharing the same name "connection", but I can't find where these function be called. Thank you!
@Ev3rlasting Those are delegate callbacks from NSURLConnection. You'll notice that when creating the NSURLConnection on line 21, the code passes self as the delegate.
@drewag Thanks for your super-fast reply! Does it mean that those three "connection" functions will all be called when line21 is called?
It looks like whoever up voted the question, also up voted the answer too. 10-10 it is.
14

_ is a placeholder parameter name. It indicates that a parameter is expected, but will not be used. in indicates the end of a closure's type signature. This whole line defines a function that takes three parameters and does nothing.

Comments

0

"_" used to make some thing anonymous.

for (key, _) in dictionary{} 

Here we make value as anonymous.

In is used to start a closure or in loop as well as we specify for the collection on which loop is applied.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.