Swift OpenWeatherMap API 类型值 'Any' 错误
Swift OpenWeatherMap API Value of type 'Any' error
嘿,我的 swift 代码出错了
Value of type 'Any' has no subscripts
在这一行
if let weatherArray = jsonObj.value(forKey: "weather") as? NSArray {
print("Type \(weatherArray[0]["main"])")
}
我不知道如何修复它我尝试在网上搜索,但我并没有找到解决方案
其余代码
let session = URLSession.shared
let weatherURL = url!
let dataTask = session.dataTask(with: weatherURL) {
(data: Data?, response: URLResponse?, error: Error?) in
if let error = error {
print("Error:\n\(error)")
}
else {
if let data = data {
let dataString = String(data: data, encoding: String.Encoding.utf8)
print("All the weather data:\n\(dataString!)")
if let jsonObj = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary {
if let mainDictionary = jsonObj.value(forKey: "main") as? NSDictionary {
if let temperature = mainDictionary.value(forKey: "feels_like") {
DispatchQueue.main.async {
print("Feels like: \(temperature)°C")
}
}
}
if let weatherArray = jsonObj.value(forKey: "weather") as? NSArray {
print("Type \(weatherArray[0]["main"])")
}
if let weatherArray = jsonObj.value(forKey: "weather") as? NSArray {
print("Type \(weatherArray[0]["main"])")
}
你必须再次将你的项目投射到 NSDictionary
if let weatherArray = jsonObj.value(forKey: "weather") as? NSArray,
let inner = weatherArray[0] as? NSDictionary {
print("Type \(inner["main"])")
}
您的 weatherArray
是一个未转换值的数组,类似于 [Any]
。当您尝试评估 weatherArray[0]["main"]
时,您正在引用类型 Any
的第一个元素并尝试获取带有下标的内容,但 Any
没有实现,因此您会收到错误。
嘿,我的 swift 代码出错了
Value of type 'Any' has no subscripts
在这一行
if let weatherArray = jsonObj.value(forKey: "weather") as? NSArray {
print("Type \(weatherArray[0]["main"])")
}
我不知道如何修复它我尝试在网上搜索,但我并没有找到解决方案
其余代码
let session = URLSession.shared
let weatherURL = url!
let dataTask = session.dataTask(with: weatherURL) {
(data: Data?, response: URLResponse?, error: Error?) in
if let error = error {
print("Error:\n\(error)")
}
else {
if let data = data {
let dataString = String(data: data, encoding: String.Encoding.utf8)
print("All the weather data:\n\(dataString!)")
if let jsonObj = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary {
if let mainDictionary = jsonObj.value(forKey: "main") as? NSDictionary {
if let temperature = mainDictionary.value(forKey: "feels_like") {
DispatchQueue.main.async {
print("Feels like: \(temperature)°C")
}
}
}
if let weatherArray = jsonObj.value(forKey: "weather") as? NSArray {
print("Type \(weatherArray[0]["main"])")
}
if let weatherArray = jsonObj.value(forKey: "weather") as? NSArray {
print("Type \(weatherArray[0]["main"])")
}
你必须再次将你的项目投射到 NSDictionary
if let weatherArray = jsonObj.value(forKey: "weather") as? NSArray,
let inner = weatherArray[0] as? NSDictionary {
print("Type \(inner["main"])")
}
您的 weatherArray
是一个未转换值的数组,类似于 [Any]
。当您尝试评估 weatherArray[0]["main"]
时,您正在引用类型 Any
的第一个元素并尝试获取带有下标的内容,但 Any
没有实现,因此您会收到错误。