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:
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)
}
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
Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.
If I want to run my closure, I call it like a function myClosure() . This will cause the code to print the current value of counter . By writing [counter] in we create a capture list that takes a snapshot of the current value of counter which will cause us to ignore any changes that are made to counter .
A closure is said to escape a function when the closure is passed as an argument to the function, but is called after the function returns. When you declare a function that takes a closure as one of its parameters, you can write @escaping before the parameter's type to indicate that the closure is allowed to escape.
Closure can be assigned to a variable outside function You can assign a closure to a variable outside the function.
OOPS nevermind...
public func queryAllFlightsWithClosure(completionHandler : (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void ) {
took out the {} and it seems to work?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With