2

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?

4

1 回答 1

5

这称为尾随闭包语法。如果函数的最后一个参数是闭包,则可以将它放在紧跟在前面参数周围的右括号之后的花括号中。

这里的get方法有两个参数:一个String和一个带有一些签名的闭包,比如(Request) -> ()

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

您还将看到唯一参数是闭包的情况,例如map()数组上的方法。在这些情况下,括号可以完全省略,闭包写在紧跟在函数名后面的花括号中,例如:

let lowerCasedWords = arrayOfWords.map{ $0.lowercased() }
于 2016-12-06T05:56:02.050 回答