xcode Swift:如何将闭包作为函数参数传入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26632129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 06:01:52  来源:igfitidea点击:

Swift: How to pass in a closure as a function argument

iosxcodeswift

提问by Jeef

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:

我想将查询修改为:

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

但它一直给我一个错误

采纳答案by Jeef

OOPS nevermind...

哎呀没关系...

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

took out the {} and it seems to work?

取出 {},它似乎工作?

回答by Antonio

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 MyClosurewith what it is aliasing, and you have the right syntax:

但是,只需将MyClosure其替换为别名,您就有正确的语法:

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