what do “_” and “in” mean in Swift programming language?

匿名 (未验证) 提交于 2019-12-03 01:14:02

问题:

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:

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



回答2:

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



回答3:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!