Jeef Jeef - 3 months ago 8
Swift Question

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:

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

Answer

OOPS nevermind...

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

took out the {} and it seems to work?

Comments