Swift:如何将闭包作为函数参数传入 [英] Swift: How to pass in a closure as a function argument
本文介绍了Swift:如何将闭包作为函数参数传入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图找出将闭包(完成处理程序)作为参数传递给另一个函数的语法.
I'm trying to figure out the syntax for passing in a closure (completion handler) as an argument to another function.
我的两个功能是:
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>) {
这样我就可以从外部将闭包传递给函数.我知道有一些对训练闭包的支持,但我不确定这是否也是可行的方法.我似乎无法正确使用语法...
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...
我试过了:
public func queryAllFlightsWithClosure(completionHandler : {(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void} ) {
但它一直给我一个错误
推荐答案
OOPS nevermind...
OOPS nevermind...
public func queryAllFlightsWithClosure(completionHandler : (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void ) {
取出 {} 似乎可以工作?
took out the {} and it seems to work?
这篇关于Swift:如何将闭包作为函数参数传入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文