Swift,字典解析错误

时间:2016-10-19 05:28:29

标签: swift xcode dictionary nsdictionary

我使用API​​来获取天气状况,检索到的字典是

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";
    };
}

如果我想要湿度的值,我只需使用

let humidityValue = dict["main"]["humidity"]并且有效。

但问题是我还希望在天气

中获得描述的价值

当我使用let dscptValue = dict["weather"]["description"]

它检索到了无。

怎么样?我注意到天气周围有两个括号。我不确定它与没有括号的语句是否相同。

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

如何获得描述的价值?

2 个答案:

答案 0 :(得分:2)

天气是一系列词典。

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

可能会给你预期的结果。

答案 1 :(得分:2)

weather个密钥包含Array Dictionary而不是直接Dictionary,因此您需要访问其中的第一个对象。

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

注意:我使用if let的可选包装来防止强制包装崩溃。