如何访问在Swift中闭包内的变量?

问题描述:

我刚开始使用Swift,我想从这个函数中获取结果。我不知道如何访问闭包内部的变量,该变量从闭包外部传递给sendAsynchronousRequest函数。我已经阅读关于闭包的章节在苹果Swift指南,我没有找到答案,我没有找到一个在*有帮助。我不能将'json'变量的值赋给'dict'变量,并且在锁之外有该棒。

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 sendAsynchronousRequest function from outside the closure. I have read the chapter on closures in the Apple Swift guide and I didn't find an answer and I didn't find one on * that helped. I can't assign the value of the 'json' variable to the 'dict' variable and have that stick outside of 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


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)

在闭包实际完成之前被调用。如果你想使用dict完成另一个函数,那么你需要从闭包中调用该函数,如果你喜欢,你可以将它移动到主线程,如果你要影响UI,你会这样做。 p>

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)
}