-1

I got this Error

Type 'Any' has no subscript members

on the lines with 'dayZeroTemperatureMax, dayZeroTemperatureMin' ect and I don't know how to fix it. I searched on the internet but all their fixes won't fix my problem. This is what i got:

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)

      }

}
Dani Kemper
  • 343
  • 2
  • 10
  • 1
    Don't use `NSArray` / `NSDictionary` in Swift. Both don't provide type information. This causes the error – vadian Sep 03 '18 at 16:51

1 Answers1

0

Swift does not know what type weeklyForcast[0] is, so you should do the following:

if let zeroWeeklyForecast = weeklyForcast[0] as? [String: Int] {
    dayOneTemperatureMax = zeroWeeklyForecast["temperatureMax"]
    dayOneTemperatureMin = zeroWeeklyForecast["temperatureMin"]
}

If weeklyForcast[0] is a [String: Any] and not [String: Int] you would have to cast from Any to Int as well.

As mentioned in the comments, NSDictionary should no longer be used in Swift and should be replaced by [Type1: Type2]. More importantly, if you are decoding data from JSON, you should consider using JSONDecoder. Here is a good tutorial.

regina_fallangi
  • 2,080
  • 2
  • 18
  • 38