Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what do "_" and "in" mean in Swift programming language?

Tags:

swift

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!

like image 657
Ev3rlasting Avatar asked Jun 17 '14 18:06

Ev3rlasting


People also ask

What is the use of _ in Swift?

In Swift, the underscore operator (_) represents an unnamed parameter/label. In for loops, using the underscore looping parameter is practical if you do not need the looping parameter in the loop. In function calls, you can omit the argument label by adding a (_) in front of the argument in the implementation.

What does underscore mean in Swift?

There are a few nuances to different use cases, but generally an underscore means "ignore this". When declaring a new function, an underscore tells Swift that the parameter should have no label when called — that's the case you're seeing.

What does ampersand mean in Swift?

In Swift, the ampersand (&) indicates that a parameter is being passed inout. Consider this example: Code Block. func addVarnish(_ product: inout String) { product += " varnish"

What is an in/out parameter in Swift?

Swift inout parameter is a parameter that can be changed inside the function where it's passed into. To accept inout parameters, use the inout keyword in front of an argument. To pass a variable as an inout parameter, use the & operator in front of the parameter.


2 Answers

_ 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.

like image 68
drewag Avatar answered Sep 24 '22 06:09

drewag


_ 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.

like image 20
Chuck Avatar answered Sep 24 '22 06:09

Chuck