How do I access variables that are inside closures in Swift?

后端 未结 2 1019
有刺的猬
有刺的猬 2021-01-19 15:05

I\'m new to Swift and I\'m trying to get the result from this function. I don\'t know how to access variables that are inside the closure that is passed to the sendAsynchron

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-19 16:02

    var dict: NSDictionary! // Declared in the main thread
    

    The closure is then completed asynchronously so the main thread doesn't wait for it, so

    println(dict)
    

    is called before the closure has actually finished. If you want to complete another function using dict then you will need to call that function from within the closure, you can move it into the main thread if you like though, you would do this if you are going to be affecting 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)
    }
    

提交回复
热议问题