简体   繁体   English

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

[英]Swift: How to pass in a closure as a function argument

I'm trying to figure out the syntax for passing in a closure (completion handler) as an argument to another function. 我试图找出传递一个闭包(完成处理程序)作为另一个函数的参数的语法。

My two functions are: 我的两个职能是:

Response Handler: 响应处理程序:

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

}

Query Function 查询功能

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)

}

I'd like to modify the Query to something like: 我想将Query修改为:

public fund queryAllFlightsWithClosure( <CLOSURE>) {

so that I can externally pass the closure into the function. 这样我就可以从外部将闭包传递给函数了。 I know there is some support for training closures but I"m not sure if thats the way to go either. I can't seem to get the syntax correct... 我知道有一些关于训练闭包的支持,但我不确定这是否也是如此。我似乎无法使语法正确...

I've tried: 我试过了:

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

but it keeps giving me an error 但它一直给我一个错误

It might help defining a type alias for the closure: 它可能有助于为闭包定义类型别名:

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

that makes the function signature "lighter" and more readable: 这使得函数签名“更轻”,更具可读性:

public func queryAllFlightsWithClosure(completionHandler : MyClosure ) {        
}

However, just replace MyClosure with what it is aliasing, and you have the right syntax: 但是,只需将MyClosure替换为别名,并使用正确的语法:

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

OOPS nevermind... OOPS没关系......

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

took out the {} and it seems to work? 取出{}它似乎有用吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM