我收到此错误
“任意”类型没有下标成员
与“ dayZeroTemperatureMax,dayZeroTemperatureMin”等类似的行,我不知道如何解决。我在互联网上进行了搜索,但是他们的所有修复程序都无法解决我的问题。这就是我得到的:
struct Weekly {
var dayZeroTemperatureMax: Int
var dayZeroTemperatureMin: Int
var dayOneTemperatureMax: Int
var dayOneTemperatureMin: Int
var dayOneTime: String?
var dayOneIcon: UIImage
init (weatherDictionary: NSDictionary) {
let weeklyWeather = weatherDictionary["daily"] as! NSDictionary
let weeklyForcast = weeklyWeather["data"] as! NSArray
//DAY ZERO
dayZeroTemperatureMax = weeklyForcast[0]["temperatureMax"] as! Int
dayZeroTemperatureMin = weeklyForcast[0]["temperatureMin"] as! Int
//DAY ONE
dayOneTemperatureMax = weeklyForcast[1]["temperatureMax"] as! Int
dayOneTemperatureMin = weeklyForcast[1]["temperatureMin"] as! Int
let dayOneTimeIntValue = weeklyForcast[1]["sunriseTime"] as! Int
dayOneTime = weeekDateStringFromUnixtime(dayOneTimeIntValue)
let dayOneIconString = weeklyForcast[1]["icon"] as! String
dayOneIcon = weatherIconFromString(dayOneIconString)
}
}
答案 0 :(得分:0)
Swift不知道weeklyForcast[0]
是什么类型,因此您应该执行以下操作:
if let zeroWeeklyForecast = weeklyForcast[0] as? [String: Int] {
dayOneTemperatureMax = zeroWeeklyForecast["temperatureMax"]
dayOneTemperatureMin = zeroWeeklyForecast["temperatureMin"]
}
如果weeklyForcast[0]
是[String: Any]
而不是[String: Int]
,则您也必须从Any
投射到Int
。
如评论中所述,NSDictionary
不应再在Swift中使用,而应由[Type1: Type2]
代替。更重要的是,如果您要从JSON解码数据,则应考虑使用JSONDecoder
。 Here是一个很好的教程。