[英]How to understand this GCDWebServer swift unit test code?
我遇到了這段代碼:
class WebServerTests: XCTestCase {
let webServer: GCDWebServer = GCDWebServer()
var webServerBase: String!
/// Setup a basic web server that binds to a random port and that has one default handler on /hello
private func setupWebServer() {
webServer.addHandlerForMethod("GET", path: "/hello", requestClass: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse! in
return GCDWebServerDataResponse(HTML: "<html><body><p>Hello World</p></body></html>")
}
我對webServer.addHandlerForMethod
部分感到困惑。 在我看來,它已經是一個完整的函數調用( webServer.addHandlerForMethod("GET", path: "/hello", requestClass: GCDWebServerRequest.self)
)。 因此,我不明白為什么要緊跟一個閉包( {(request) -> ...
)
編輯 :澄清我不明白的內容
根據https://github.com/swisspol/GCDWebServer上的文檔,obj-c中的函數簽名為:
[webServer addDefaultHandlerForMethod:@"GET"
requestClass:[GCDWebServerRequest class]
asyncProcessBlock:^(GCDWebServerRequest* request, GCDWebServerCompletionBlock completionBlock) {
因此,我希望它的快速對應對象會這樣稱呼:
webServer.addHandlerForMethod("GET", path: "/hello", requestClass: GCDWebServerRequest.self, { (request) -> GCDWebServerResponse! in
return GCDWebServerDataResponse(HTML: "<html><body><p>Hello World</p></body></html>")
})
即傳入請求的處理作為第三個參數傳遞。 但是由於閉包在閉包')'之后,所以它看起來根本不像函數調用的一部分。
為什么函數簽名從obj-c映射到swift這種方式?
關閉是處理傳入請求的地方。 當請求/hello
路徑的GET
方法到來時,它告訴服務器運行閉包的代碼。
在您在閉包中發布代碼的代碼中,將創建服務器返回的響應。
在Swift中,如果函數的最后一個參數是閉包,則可以使用此語法。 這是Swift語言指南部分中關於閉包的示例(向下滾動到Trailing Closures ):
func someFunctionThatTakesAClosure(closure: () -> ()) {
// function body goes here
}
// here's how you call this function without using a trailing closure:
someFunctionThatTakesAClosure({
// closure's body goes here
})
// here's how you call this function with a trailing closure instead:
someFunctionThatTakesAClosure() {
// trailing closure's body goes here
}
然后還有這個注釋:
如果將閉包表達式作為函數的唯一參數提供,並且將該表達式作為尾隨閉包提供,則在調用函數時,無需在函數名稱后寫一對括號()。
這意味着編寫此代碼也是合法的:
someFunctionThatTakesAClosure {
// closure body
}
……這有助於提供一種不錯的元編程語法。 例如:
let lock = NSLock()
func locked(closure: () -> ()) {
lock.lock();
closure()
lock.unlock();
}
locked {
NSLog("Hello, world!")
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.