使用未解析的标识符 'json' (Swift 3) (Alamofire)
Use of unresolved identifier 'json' (Swift 3) (Alamofire)
我收到错误消息:使用未解析的标识符 '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.
我收到错误消息:使用未解析的标识符 '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.