【问题标题】:Use of unresolved identifier 'json' (Swift 3) (Alamofire)使用未解析的标识符 'json' (Swift 3) (Alamofire)
【发布时间】:2017-04-15 21:19:52
【问题描述】:

我收到错误:使用未解析的标识符“json”

从此行:if let data = json["data"] ...

这是错误相关代码的sn-p

        // check response & if url request is good then display the results
        if let json = response.result.value! as? [String: Any] {

            print("json: \(json)")
        }

        if let data = json["data"] as? Dictionary<String, AnyObject> {
            if let weather = data["weather"] as? [Dictionary<String, AnyObject>] {
                if let uv = weather[0]["uvIndex"] as? String {
                    if let uvI = Int(uv) {
                        self.uvIndex = uvI
                        print ("UV INDEX = \(uvI)")
                    }
                }
            }
        }

【问题讨论】:

    标签: json swift3 alamofire swifty-json


    【解决方案1】:

    您有范围界定问题。 json 变量只能在 if let 语句中访问。

    要解决这个问题,一个简单的解决方案是将其余代码移动到第一个 if let 语句的大括号内:

    if let json = response.result.value! as? [String: Any] {
        print("json: \(json)")
        if let data = json["data"] as? Dictionary<String, AnyObject> {
            if let weather = data["weather"] as? [Dictionary<String, AnyObject>] {
                if let uv = weather[0]["uvIndex"] as? String {
                    if let uvI = Int(uv) {
                        self.uvIndex = uvI
                        print ("UV INDEX = \(uvI)")
                    }
                }
            }
        }
    }
    

    从您的代码中可以看出,嵌套开始使您的代码难以阅读。避免嵌套的一种方法是使用guard 语句,它将新变量保留在外部范围内。

    guard let json = response.result.value else { return }
    
    // can use the `json` variable here
    if let data = json["data"] // etc.
    

    【讨论】:

    • 谢谢您,解决了范围界定问题,解决了问题!
    • 太棒了!如果您将我的答案标记为已接受,那么将来遇到相同问题的其他人将更容易找到。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    相关资源
    最近更新 更多