嘿,我的swift代码给出了一个错误
"Any"类型的值没有下标
在行中
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
没有实现,因此会出现错误。