2

I am doing my first steps in Vapor, the web framework for Swift.

The first piece of code that called my attention was this:

app.get("welcome") { request in 
    return "Hello"
}

I don't understand the syntax here. I mean, I'm calling app.get() method, but I'm also defining some kind of function where request is a parameter. I know that this will result in a get method accessible by a /welcome URL and will return "Hello". What is not clear for me is how this piece of code works and how the compiler interprets it.

Rob Forrest
  • 7,329
  • 7
  • 52
  • 69
Alberto Cruz
  • 137
  • 3
  • 9
  • Do CMD+Click on `.get` and you will see the method declaration, it will be enlightening. :) Keywords: callback (completion handler) and trailing closures. – Eric Aya Nov 14 '16 at 15:43
  • Oh. No Xcode, so... Vim? ;) Ok, you won't see the method declaration, but you can still have a look at those keywords. Have a look at [this answer](http://stackoverflow.com/a/37343547/2227743), it shows a similar trailing closure example. – Eric Aya Nov 14 '16 at 15:47
  • Thanks! I saw it is a completion handler. So it is just a callback. Thanks a lot! – Alberto Cruz Nov 14 '16 at 15:48

1 Answers1

4

This is called trailing closure syntax.

I give a nice rundown of the various syntactic sugars of closures in this answer.

The expanded version of this code would be:

app.get("welcome", { (request: Request) throws -> ResponseRepresentable in 
    return "Hello"
})
Community
  • 1
  • 1
Alexander
  • 59,041
  • 12
  • 98
  • 151