Swift `in` keyword meaning?

Martin picture Martin · May 21, 2015 · Viewed 24.4k times · Source

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?

Answer

matt picture matt · May 21, 2015

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