4

I am using Vapor and one of the first thing is to use get method which looks like following:

drop.get("hello") { request in
    return "Hello, world!"
}

Now my understanding was that the closures are like variable of type functions. Correct? Here I see we call a method get on an instance of Droplet class called drop and pass in a string.

What is with the closure being called/passed inside the get method body? How do I read this?

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
java_doctor_101
  • 3,287
  • 4
  • 46
  • 78

1 Answers1

8

This is called trailing closure syntax. If the last parameter of a function is a closure, it can be placed in curly braces immediately following a closing parenthesis around the previous parameters.

The get method here takes two parameters: a String and a closure with some signature like (Request) -> ()

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html#//apple_ref/doc/uid/TP40014097-CH11-ID102

You'll also see cases where the only parameter is a closure, like the map() method on an array. In these situations, the parentheses can be omitted entirely and the closure is written in curly braces immediately following the function name, e.g.:

let lowerCasedWords = arrayOfWords.map{ $0.lowercased() }
Daniel Hall
  • 13,457
  • 4
  • 41
  • 37