Jeef
Jeef

Reputation: 27285

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

Upvotes: 12

Views: 14625

Answers (2)

Antonio
Antonio

Reputation: 72800

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:

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

Upvotes: 12

Jeef
Jeef

Reputation: 27285

OOPS nevermind...

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

took out the {} and it seems to work?

Upvotes: 3

Related Questions