ios Swift`in` 关键字的含义?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30379108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift `in` keyword meaning?
提问by Martin
I am trying to implement some code from parse.com and I notice a keyword in
after the void.
我正在尝试从 parse.com 实现一些代码,我注意到in
void 后面有一个关键字。
I am stumped what is this ? The second line you see the Void in
我难住了这是什么?你看到的第二行Void in
PFUser.logInWithUsernameInBackground("myname", password:"mypass") {
(user: PFUser?, error: NSError?) -> Void in
if user != nil {
// Do stuff after successful login.
} else {
// The login failed. Check error to see why.
}
}
The docs don't document this. I know the in
keyword is used in for
loops.
文档没有记录这一点。我知道in
关键字在for
循环中使用。
Anyone confirm?
有人确认吗?
回答by matt
In a named function, we declare the parameters and return type in the func
declaration line.
在命名函数中,我们在func
声明行中声明参数和返回类型。
func say(s:String)->() {
// body
}
In an anonymous function, there is no func
declaration line - it's anonymous! So we do it with an in
line at the start of the body instead.
在匿名函数中,没有func
声明行——它是匿名的!所以我们in
在正文的开头用一行来代替。
{
(s:String)->() in
// body
}
(That is the fullform of an anonymous function. But then Swift has a series of rules allowing the return type, the parameter types, and even the parameter names and the whole in
line to be omitted under certain circumstances.)
(这是匿名函数的完整形式。但 Swift 有一系列规则,允许in
在某些情况下省略返回类型、参数类型,甚至参数名称和整行。)
回答by Tony
*
*
The start of the closure's body is introduced by the in keyword. This keyword indicates that the definition of the closure's parameters and return type has finished, and the body of the closure is about to begin.
闭包主体的开始由 in 关键字引入。这个关键字表示闭包的参数和返回类型的定义已经完成,闭包的主体即将开始。
*
*
来源:https: //developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html