Ios 使用swift 3解析JSON时,获取(类型any没有下标成员)错误
当我运行这段代码时,它会在我试图获取天气id的块上抛出一个错误 类型Any没有下标成员 我尝试将其转换为类型Ios 使用swift 3解析JSON时,获取(类型any没有下标成员)错误,ios,json,swift,xcode,swift3,Ios,Json,Swift,Xcode,Swift3,当我运行这段代码时,它会在我试图获取天气id的块上抛出一个错误 类型Any没有下标成员 我尝试将其转换为类型any,并将Anyobject更改为any,但这似乎不起作用 func getWeather(city: String) { // This is a pretty simple networking task, so the shared session will do. let session = URLSession.shared
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()
尝试强制转换到无法订阅的任何对象。NSArray和NSDictionary可以。您需要将对象强制转换为正确的类型,然后为其下标。希望这有所帮助。当您想要访问容器的内部元素时,可以使用下标。
使用索引为数组下标,使用键为字典下标 Swift是一种静态类型语言,意思是即使当你告诉编译器它是
Any
类型时,某个东西返回了一个字典……那么编译器会将它视为这样(键入Any而不是type dictionary),并且对于这样的类型,没有下标的能力。一旦你从类型Any
中得到了一些东西,你就必须使用作为关键字来向下转换它
let JSONItem as Dictionary
您需要在上次使用下标之前添加另一个强制转换。您需要使用的铸件取决于您期望的类型。例如,如果您期望
weather[“weather”][0]要成为[String:AnyObject]类型的字典,请更改此行:
打印(“天气ID:(天气[“天气”![0]![“ID”]!!)”
关于这一行:
打印(“天气ID:((天气[“天气”]![0]!as![String:AnyObject])[“ID”!)”)请在发布前打印。