Swift `in`关键字是什么意思?

Swift `in` keyword meaning?

我正在尝试实现 parse.com 中的一些代码,我注意到 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.
  }
}

文档没有记录这一点。我知道 in 关键字用于 for 循环。

有人确认吗?

在命名函数中,我们在 func 声明行中声明参数和 return 类型。

func say(s:String)->() {
    // body
}

在匿名函数中,没有 func 声明行 - 它是匿名的!所以我们在正文的开头使用 in 行来代替。

{
    (s:String)->() in
    // body
}

(即full形式的匿名函数。但是Swift有一系列规则允许return类型,参数类型,甚至参数名称和整个 in 行在某些情况下也会被省略。)

*

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.

*

来源: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html

闭包表达式语法具有以下一般形式:

in 服务的目的是什么的问题在这里已经被其他用户很好地回答了;总结: in 是在 Swift 闭包语法中定义的关键字,作为闭包中函数类型和函数体之间的分隔符:

{ /parameters and type/ in /function body/ }

但对于那些可能想知道“但为什么要特别使用关键字 in?”的人来说,这里有一些历史,由 Apple 高级 Swift 编译器工程师 Joe Groff 在 Swift forums:

It's my fault, sorry. In the early days of Swift, we had a closure syntax that was very similar to traditional Javascript:

func (arg: -> Type, arg: Type) -> Return { ... }

While this is nice and regular syntax, it is of course also very bulky and awkward if you're trying to support expressive functional APIs, such as map/filter on collections, or if you want libraries to be able to provide closure-based APIs that feel like extensions of the language.

Our earliest adopters at Apple complained about this, and mandated that we support Ruby-style trailing closure syntax. This is tricky to fit into a C-style syntax like Swift's, and we tried many different iterations, including literally Ruby's {|args| } syntax, but many of them suffered from ambiguities or simply distaste and revolt from our early adopters. We wanted something that still looked like other parts of the language, but which could be parsed unambiguously and could span the breadth of use cases from a fully explicit function signature to extremely compact.

We had already taken in as a keyword, we couldn't use -> like Java does because it's already used to denote the return type, and we were concerned that using => like C# would be too visually confusing. in made xs.map { x in f(x) } look vaguely like for x in xs { f(x) }, and people hated it less than the alternatives.

*格式化和强调我的。还要感谢 Swift 论坛上的 Nikita Belov's post 帮助我自己理解。