问题 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)")

}

查询功能

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)

}

我想将Query修改为:

public fund queryAllFlightsWithClosure( <CLOSURE>) {

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

我试过了:

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

但它一直给我一个错误


5610
2017-10-29 13:51


起源



答案:


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

public typealias MyClosure = (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void

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

public func queryAllFlightsWithClosure(completionHandler : MyClosure ) {        
}

但是,只需更换 MyClosure 什么是别名,你有正确的语法:

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

12
2017-10-29 13:56



但是如何在Closure中传递返回值 - Vikash Rajput


答案:


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

public typealias MyClosure = (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void

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

public func queryAllFlightsWithClosure(completionHandler : MyClosure ) {        
}

但是,只需更换 MyClosure 什么是别名,你有正确的语法:

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

12
2017-10-29 13:56



但是如何在Closure中传递返回值 - Vikash Rajput


OOPS没关系......

public func queryAllFlightsWithClosure(completionHandler : (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void ) {

取出{}它似乎有用吗?


3
2017-10-29 13:53



是的,这是正确的 - 在实现闭包体时要使用的括号 - Antonio