【问题标题】:How do I access variables that are inside closures in Swift?如何访问 Swift 中闭包内的变量?
【发布时间】:2015-10-30 23:15:46
【问题描述】:

我是 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

【问题讨论】:

  • 闭包的全部意义在于闭包内的语句异步完成。这意味着当您尝试在其外部打印 dict 时,关闭尚未完成。这意味着你想用 dict 做的事情应该在闭包中完成。
  • 没错,@SwiftRabbit 是对的。

标签: ios xcode swift scope closures


【解决方案1】:
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)
}

【讨论】:

  • 谢谢,但是当我尝试使用主线程时,我得到了“无法使用“(NSDictionary)”类型的参数列表调用“myFunction”。
  • 已修改代码以修复该错误,dict 需要在使用 ! 将其传递给函数之前解包。
  • 编辑:收到错误无法使用类型为“(dispatch_queue_t!,()-> Void)”的参数列表调用“dispatch_async”
  • 请把你的代码发给我,我需要看看它在什么样的上下文中,是否是一个功能等等
  • 我几天前就找到了问题的根源。这真的是一个非常简单的错误。我创建了一个静态函数,却忘记了我已经将其设置为静态,这就是导致所有问题的原因。
【解决方案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 请求完成后执行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-03
    • 1970-01-01
    • 2017-06-25
    • 1970-01-01
    • 2011-10-20
    • 2011-04-11
    • 1970-01-01
    • 2012-11-28
    相关资源
    最近更新 更多