Search code examples
jsonswiftios8nsarraynsdictionary

Trying to get a String out of an Array (Open Weather Map)


I am trying to get weather data from the Open Weather Map API (json) using swift. I managed to access the temperature using this

if let main = json["main"] as? NSDictionary {
    println(main)
    if var temp = main["temp"] as? Double {
        temperatureLabel.text = String(format: "%.1fº K", temp)
    }
}

Unfortunatly I am not able to access the weather description! I tried

if let weather = json["weather"] as? NSArray {
    println(weather)
    if var temp = weather["description"] as? String {
        descriptionLabel.text = weatherDescription
    }
}

I just don't know what to try anymore due to the fact that I am new to Swift and never used json before.


Solution

  • weather is an array of dictionaries so the array needs to be subscripted as following:

    if let weather = json["weather"] as? NSArray {
        println(weather)
        if var temp = weather[0]["description"] as? String {
            descriptionLabel.text = weatherDescription
        }
    }