我收到错误:使用未解析的标识符"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.