How do I access variables that are inside closures in Swift?
I am new to Swift and I am trying to get the result from this function. I don't know how to access the variables inside the closure that is passed to the sendAsynchronousRequest function due to the closure. I read the chapter on closing in Apple's Swift manual and I didn't find an answer and I didn't find one on StackOverflow that helped. I cannot assign the value of the "json" variable to the "dict" variable and stick with this stick outside the closure.
var dict: NSDictionary!
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response, data, error) in
var jsonError: NSError?
let json = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: &jsonError) as? NSDictionary
dict = json
print(dict) // prints the data
})
print(dict) // prints nil
source to share
var dict: NSDictionary! // Declared in the main thread
The closure completes asynchronously, so the main thread doesn't wait for it, so
println(dict)
called before the close completes. If you want to execute another function using a dict, you will need to call that function from within the closure, you can move it to the main thread if you want, but that would if you are going to influence the UI.
var dict: NSDictionary!
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response, data, error) in
var jsonError: NSError?
let json = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: &jsonError) as? NSDictionary
dict = json
//dispatch_async(dispatch_get_main_queue()) { //uncomment for main thread
self.myFunction(dict!)
//} //uncomment for main thread
})
func myFunction(dictionary: NSDictionary) {
println(dictionary)
}
source to share
You call an asynchronous function and print act
without waiting for it to complete. In other words, when called print(dict)
, the function is not fully executed (hence dict
is nil
)
Try something like
var dict: NSDictionary!
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response, data, error) in
var jsonError: NSError?
let json = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: &jsonError) as? NSDictionary
dict = json
doSomethingWithJSON(dict)
})
and put your JSON logic inside a function doSomethingWithJSON
:
void doSomethingWithJSON(dict: NSDictionary) {
// Logic here
}
This will ensure that your logic is only executed after the URL request completes.
source to share