【问题标题】:How to understand this GCDWebServer swift unit test code?如何理解这个 GCDWebServer swift 单元测试代码?
【发布时间】:2015-03-19 06:13:52
【问题描述】:

我遇到过这段代码:

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>")
        }

我对@9​​87654323@ 部分感到困惑。在我看来,它已经是一个完整的函数调用(webServer.addHandlerForMethod("GET", path: "/hello", requestClass: GCDWebServerRequest.self))。因此我不明白为什么它后面跟着一个闭包({(request) -&gt; ...

编辑:澄清我不明白的地方

根据https://github.com/swisspol/GCDWebServer上的文档,obj-c中的函数签名是:

[webServer addDefaultHandlerForMethod:@"GET"
                         requestClass:[GCDWebServerRequest class]
                    asyncProcessBlock:^(GCDWebServerRequest* request, GCDWebServerCompletionBlock completionBlock) {

因此,我希望它的 swift 对应物将被称为有点像这样:

        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的?

【问题讨论】:

    标签: swift gcdwebserver


    【解决方案1】:

    闭包是处理传入请求的地方。当请求/hello 路径的GET 方法到来时,它告诉服务器运行闭包的代码。

    在您发布的代码中,闭包中的代码会创建服务器返回的响应。

    【讨论】:

    • 非常感谢,感谢您的回答!但是我认为我的问题更多是关于这种特殊形式的语法,而不是代码的作用。我更新了我的问题以澄清我不明白的地方。
    【解决方案2】:

    在 Swift 中,如果函数的最后一个参数是闭包,则可以使用此语法。这是来自Swift language guide section about 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!")
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-03
      • 2017-08-10
      • 2021-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多