简体   繁体   English

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

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

I'm new to Swift and I'm trying to get the result from this function. 我是Swift的新手,我正试图从这个函数中得到结果。 I don't know how to access variables that are inside the closure that is passed to the sendAsynchronousRequest function from outside the closure. 我不知道如何访问闭包内部的变量,该变量从闭包外部传递给sendAsynchronousRequest函数。 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 StackOverflow that helped. 我已经阅读了Apple Swift指南中有关闭包的章节,我没有找到答案,而且我没有在StackOverflow上找到一个有帮助的答案。 I can't assign the value of the 'json' variable to the 'dict' variable and have that stick outside of the closure. 我不能将'json'变量的值赋给'dict'变量,并在闭包之外使用该棒。

    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)

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. 如果你想使用dict完成另一个函数,那么你需要从闭包中调用该函数,如果你愿意,可以将它移动到主线程中,如果你要影响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)
}

You are calling an asynchronous function and printing act without waiting for it to finish. 您正在调用异步函数并打印act而无需等待它完成。 In other words, when print(dict) is called, the function hasn't complete execution(hence dict is nil ) 换句话说,当调用print(dict) ,函数没有完成执行(因此dictnil

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 doSomethingWithJSON function: 并将您的JSON逻辑放在doSomethingWithJSON函数中:

void doSomethingWithJSON(dict: NSDictionary) {
    // Logic here
}

This ensures that your logic is execute only after the URL request completes. 这可确保您的逻辑仅在URL请求完成后执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM