Alberto Cruz Alberto Cruz - 1 year ago 78
Swift Question

Parameters after opening bracket

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 syntaxis here. I mean, Imm 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.

Answer Source

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) -> Response in 
    return "Hello"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download