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

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

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

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

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

您正在调用一个异步函数并打印 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 请求完成后执行。