【问题标题】:Closure data cannot be accessed outside its scope闭包数据不能在其范围之外访问
【发布时间】:2017-04-27 01:47:26
【问题描述】:

我正在使用 Alamofire 向 API 发出异步网络请求。在闭包内,我将响应的数据分配给特定变量(championRolesLibrary)。现在在闭包内,当我打印变量以查看其内容(项目 1)时,它包含我希望它拥有的所有数据。在闭包表达式(项目 2 )之外,当检查同一个对象并且在 1 和 2 之间没有以任何方式修改时,它不再有任何数据并且是空的。为什么是这样?

Alamofire.request(championRolesUrl!).responseJSON { response in
    let result = response.result
        if result.isSuccess {
            if let data = result.value as? [[String:AnyObject]] {
                for champion in data {
                    if let name = champion["name"] as? String {

                        if let roles = champion["roles"] as? Array<Dictionary<String, AnyObject>> {
                            championRoles = []
                            for role in roles {
                                if let roleName = role["name"] as? String {
                                    championRoles.append(Role(roleName)!)
                                }
                            }
                            championRolesLibrary.append([name:championRoles])
                        }
                    }
                }
                print(championRolesLibrary) // 1
            }
        } else {
            print("Downloading Role Data Failed Because: \(result.error)")
        }
    }
}
print(championRolesLibrary) // 2

【问题讨论】:

  • 在两个打印语句上设置断点并注意它们的调用顺序。

标签: ios swift scope closures


【解决方案1】:

Alamofire's documentation 说:

Alamofire 中的网络是异步完成的。异步 编程可能是不熟悉的程序员的挫败感 有了这个概念,但这样做有很好的理由 方式。

这意味着当您发出请求时,您是在异步进行的,因此当您在闭包之外打印 championRolesLibrary 时,实际上是在您的请求返回数据之前打印它。

【讨论】:

    【解决方案2】:

    闭包是可以在代码中传递和使用的独立功能块。 Swift 中的闭包类似于 C 和 Objective-C 中的块以及其他编程语言中的 lambda。

    因此,在这里,您的所有代码语句在您的 Alamofire 代码执行之前执行,在执行每个语句之后,Alamofire 开始执行,这就是您没有在闭包之外获取值的原因,因为外部语句已经执行已经。

    【讨论】:

      猜你喜欢
      • 2014-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多