2017-04-15 75 views
1

我接收到錯誤:使用未解決的識別符「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)") 
        } 
       } 
      } 
     } 

回答

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. 
+1

謝謝修復範圍問題,解決了問題! –

+1

太棒了!如果您將我的答案標記爲已接受,那麼將來如果他們遇到同樣的問題,將會更容易爲其他人找到答案。 – nathan

相關問題