當我運行這段代碼時,它會在我嘗試獲取天氣ID的地方引發錯誤。使用swift解析JSON時得到一個(輸入任何沒有下標成員)錯誤3
類型的任何無標會員
我試圖鑄造它作爲any
型和改變Anyobject
到Any
但似乎並沒有工作
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()
請[在錯誤上搜索](http://stackoverflow.com/search?q=%5Bswift%5D+type+Any+has+no+subscript+成員+ json)發佈之前。 – rmaddy