Swift,字典解析错误

标签 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"] 它起作用了。

但问题是我还想获得 descriptionweather 中的值

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

它检索到 nil。

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

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

如何获取description的值?

最佳答案

weather键包含DictionaryArray,不是直接Dictionary,所以需要访问第一个对象它。

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

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

关于Swift,字典解析错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40122876/

相关文章:

ios - iPad 版 iOS App

cocoa - 嵌入式框架与 bundle 外部的版本冲突

python - 从文本中读取行并将其转换为 Python 嵌套字典

python - 在python中对相似值进行分组和求和

python - 如何使用一个键将多个列表值的数据框制作成python中的字典?

swift - 重音字母和表情符号

ios - UITableViewCell 中的 navigationItem.title

ios - fatal error : Index Out of Range : Swift

json - 如何在 Swift 中解码具有许多唯一键的嵌套 JSON?

iphone - NSString 双重问题