我收到错误:使用未解析的标识符“json”
从这一行: if let data = json["data"] ...
这是与错误相关的代码片段
// 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
变量只能在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.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句