我试图弄清楚传递一个闭包(完成处理程序)作为另一个函数的参数的语法。
我的两个职能是:
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)
}
我想将查询修改为:
public fund queryAllFlightsWithClosure( <CLOSURE>) {
这样我就可以从外部将闭包传递给函数了。我知道有一些支持训练关闭,但我不确定这是否也是如此。我似乎无法使语法正确...
我试过了:
public func queryAllFlightsWithClosure(completionHandler : {(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void} ) {
但它一直给我一个错误
答案 0 :(得分:12)
它可能有助于为闭包定义类型别名:
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 ) {
}
答案 1 :(得分:3)
OOPS没关系......
public func queryAllFlightsWithClosure(completionHandler : (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void ) {
取出{},似乎有用吗?