Swift `in` keyword meaning?

浪尽此生 提交于 2019-11-28 17:23:11

问题


I am trying to implement some code from parse.com and I notice a keyword in after the void.

I am stumped what is this ? The second line you see the 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.

Anyone confirm?


回答1:


In a named function, we declare the parameters and return type in the func declaration line.

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.

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

(That is the full form 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.)




回答2:


*

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.

*

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




回答3:


Closure expression syntax has the following general form:



来源:https://stackoverflow.com/questions/30379108/swift-in-keyword-meaning

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