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

时间:2015-08-07 13:27:18

标签: ios xcode swift scope closures

我是Swift的新手,我正试图从这个函数中获得结果。我不知道如何访问闭包内部的变量,该变量从闭包外部传递给sendAsynchronousRequest函数。我已经阅读了Apple Swift指南中有关闭包的章节,我没有找到答案,而且我没有在StackOverflow上找到一个有帮助的答案。我不能将'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

2 个答案:

答案 0 :(得分:4)

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

然后异步完成闭包,因此主线程不会等待它,所以

println(dict)
在闭包实际完成之前调用

。如果你想使用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)
}

答案 1 :(得分:2)

您正在调用异步函数并打印act而不等待它完成。换句话说,当调用print(dict)时,函数没有完成执行(因此dictnil

尝试类似

的内容
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)
})

并将您的JSON逻辑放在doSomethingWithJSON函数中:

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

这可确保您的逻辑仅在URL请求完成后执行。