2016-11-13 34 views
-2

當我運行這段代碼時,它會在我嘗試獲取天氣ID的地方引發錯誤。使用swift解析JSON時得到一個(輸入任何沒有下標成員)錯誤3

類型的任何無標會員

我試圖鑄造它作爲any型和改變AnyobjectAny但似乎並沒有工作

func getWeather(city: String) { 

     // This is a pretty simple networking task, so the shared session will do. 
     let session = URLSession.shared 

     let weatherRequestURL = URL(string: "\(openWeatherMapBaseURL)?APPID=\(openWeatherMapAPIKey)&q=\(city)")! 

     let dataTask = session.dataTask(with: weatherRequestURL) { (data: Data?, response: URLResponse?, error: Error?) in 
      if error != nil { 
       print(error) 
      }else { 

       do { 
        // Try to convert that data into a Swift dictionary 
        let weather = try JSONSerialization.jsonObject(
         with: data!, 
        options: .mutableContainers) as! [String: AnyObject]     // If we made it to this point, we've successfully converted the 
        // JSON-formatted weather data into a Swift dictionary. 
        // Let's print its contents to the debug console. 
        print("Date and time: \(weather["dt"]!)") 
        print("City: \(weather["name"]!)") 

        print("Longitude: \(weather["coord"]!["lon"]!!)") 
        print("Latitude: \(weather["coord"]!["lat"]!!)") 

        print("Weather ID: \(weather["weather"]![0]!["id"]!!)") 
        print("Weather main: \(weather["weather"]![0]!["main"]!!)") 
        print("Weather description: \(weather["weather"]![0]!["description"]!!)") 
        print("Weather icon ID: \(weather["weather"]![0]!["icon"]!!)") 

        print("Temperature: \(weather["main"]!["temp"]!!)") 
        print("Humidity: \(weather["main"]!["humidity"]!!)") 
        print("Pressure: \(weather["main"]!["pressure"]!!)") 

        print("Cloud cover: \(weather["clouds"]!["all"]!!)") 

        print("Wind direction: \(weather["wind"]!["deg"]!!) degrees") 
        print("Wind speed: \(weather["wind"]!["speed"]!!)") 

        print("Country: \(weather["sys"]!["country"]!!)") 
        print("Sunrise: \(weather["sys"]!["sunrise"]!!)") 
        print("Sunset: \(weather["sys"]!["sunset"]!!)") 
       } 
       catch let jsonError as NSError { 
        // An error occurred while trying to convert the data into a Swift dictionary. 
        print("JSON error description: \(jsonError.description)") 
       } 

      } 
     } 
     dataTask.resume() 
+2

請[在錯誤上搜索](http://stackoverflow.com/search?q=%5Bswift%5D+type+Any+has+no+subscript+成員+ json)發佈之前。 – rmaddy

回答

0

嘗試強制轉換爲任何或AnyObject不能下標。 NSArrays和NSDictionaries可以。您需要將對象轉換爲正確的類型,然後對其進行下標。希望這有助於。

0

當您喜歡訪問容器的內部元素時使用下標。
您下標數組使用索引和字典使用密鑰

斯威夫特是一個靜態類型語言的意思,即使東西返回字典你告訴它的Any類型的編譯器...那麼編譯器將對待它(鍵入任何和類型字典),對於這種類型,沒有下標的能力。一旦你從類型Any得到的東西,你必須downcast它使用as關鍵字。

let JSONItem as Dictionary 
0

您需要的最後一標使用前再添鑄造。你需要使用什麼鑄件取決於你期望的類型。例如,如果你希望
天氣[ 「天氣」] [0]是類型的詞典[字符串:AnyObject],改變這一行:

打印( 「天氣ID:(天氣[」 天氣「]! [0] [ 「ID」] !!)! 「)

向該行:

打印(」 天氣ID:((天氣[ 「天氣」] [0]爲[字符串!!!: AnyObject])[「id」]!)「)

相關問題