Swift:如何将闭包传递为函数参数

Jee*_*eef 11 xcode ios swift

我试图找出传递一个闭包(完成处理程序)作为另一个函数的参数的语法.

我的两个职能是:

响应处理程序:

func responseHandler(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void {
    var err: NSError


    var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
    println("AsSynchronous\(jsonResult)")

}
Run Code Online (Sandbox Code Playgroud)

查询功能

public func queryAllFlightsWithClosure( ) {

    queryType = .AllFlightsQuery
    let urlPath = "/api/v1/flightplan/"
    let urlString : String = "http://\(self.host):\(self.port)\(urlPath)"
    var url : NSURL = NSURL(string: urlString)!
    var request : NSURLRequest = NSURLRequest(URL: url)

        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:responseHandler)

}
Run Code Online (Sandbox Code Playgroud)

我想将Query修改为:

public fund queryAllFlightsWithClosure( <CLOSURE>) {
Run Code Online (Sandbox Code Playgroud)

这样我就可以从外部将闭包传递给函数了.我知道有一些关于训练闭包的支持,但我不确定这是否也是如此.我似乎无法使语法正确...

我试过了:

public func queryAllFlightsWithClosure(completionHandler : {(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void} ) {
Run Code Online (Sandbox Code Playgroud)

但它一直给我一个错误

Ant*_*nio 12

它可能有助于为闭包定义类型别名:

public typealias MyClosure = (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void
Run Code Online (Sandbox Code Playgroud)

这使得函数签名"更轻",更具可读性:

public func queryAllFlightsWithClosure(completionHandler : MyClosure ) {        
}
Run Code Online (Sandbox Code Playgroud)

但是,只需替换MyClosure它的别名,你就有了正确的语法:

public func queryAllFlightsWithClosure(completionHandler : (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void ) {
}
Run Code Online (Sandbox Code Playgroud)

  • 但是如何在闭包中传递返回值 (2认同)

Jee*_*eef 3

哎呀没关系...

public func queryAllFlightsWithClosure(completionHandler : (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void ) {
Run Code Online (Sandbox Code Playgroud)

拿出 {} 似乎可以工作?