Michael VEE
Michael VEE

Reputation: 117

Swift, dictionary parse error

I'm using an API to get weather condition and the retrieved dict is

dict = {
    base = stations;
    clouds =     {
        all = 92;
    };
    cod = 200;
    coord =     {
        lat = "31.23";
        lon = "121.47";
    };
    dt = 1476853699;
    id = 1796231;
    main =     {
        "grnd_level" = "1028.63";
        humidity = 93;
        pressure = "1028.63";
        "sea_level" = "1029.5";
        temp = "73.38";
        "temp_max" = "73.38";
        "temp_min" = "73.38";
    };
    name = "Shanghai Shi";
    rain =     {
        3h = "0.665";
    };
    sys =     {
        country = CN;
        message = "0.0125";
        sunrise = 1476827992;
        sunset = 1476868662;
    };
    weather =     (
        {
            description = "light rain";
            icon = 10d;
            id = 500;
            main = Rain;
        }
    );
    wind =     {
        deg = "84.50239999999999";
        speed = "5.97";
    };
}

If I want the value of humidity, I just use

let humidityValue = dict["main"]["humidity"] and it works.

But the problem is I also want to get the value of description in weather

when I used let dscptValue = dict["weather"]["description"]

it retrieved nil.

How's that? and I notice there are two brackets around weather .I'm not sure whether it is the same with the statement without brackets.

    weather =     (
            {
        description = "light rain";
        icon = 10d;
        id = 500;
        main = Rain;
    }
);

How to get the value of description?

Upvotes: 0

Views: 75

Answers (2)

Nirav D
Nirav D

Reputation: 72460

weather keys contains Array of Dictionary not directly Dictionary, so you need to access the first object of it.

if let weather = dict["weather"] as? [[String: AnyObject]], let weatherDict = weather.first {
    let dscptValue = weatherDict["description"]
}

Note: I have used optional wrapping with if let for preventing crash with forced wrapping.

Upvotes: 2

Raphael Oliveira
Raphael Oliveira

Reputation: 7841

Weather is an array of dictionaries.

dict["weather"][0]["description"] 

may give you the expected result.

Upvotes: 2

Related Questions