使用未解决的识别符的“JSON”(SWIFT 3)(Alamofire)
问题描述:
我接收到错误:使用未解决的识别符“JSON”使用未解决的识别符的“JSON”(SWIFT 3)(Alamofire)
从该行的: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.
谢谢修复范围问题,解决了问题! –
太棒了!如果您将我的答案标记为已接受,那么将来如果他们遇到同样的问题,将会更容易为其他人找到答案。 – nathan