arrays - 在 Swift 中反序列化一个以数组作为值的字典

标签 arrays swift dictionary serialization

在 Swift 4 中,我有一个字典,其中包含来自网络服务器的响应。在字典中,我有 3 对键和值。其中之一是数组。如何访问整个数组?

打印时

print(result["top10"]

我得到了这样的东西

{
    item =     (
                {
            count = 233;
            "engine_size" = "3,0";
            "fuel_type" = Otto;
            "vehicle_brand" = Audi;
            "vehicle_type" = "A4_8K";
        },
                {
            count = 107;
            "engine_size" = "3,0";
            "fuel_type" = Diesel;
            "vehicle_brand" = Audi;
            "vehicle_type" = "A6_4G0";
        };
}

我期望这样的数据:

top10[0].count == "223"
top10[0].count == "3,0"

top10[1].count == "107"
top10[1].count == "3,0"

等等

最佳答案

您的阵列不是 Top10。 Top10 是一个字典,其中包含其中的“项目”列表。所以,你想要的数组实际上是 top10 字典中的“item”数组。通过 result["top10"] 的打印,我可以看到 top10["item"] 是 Top10 中的字典数组。 像这样尝试:

if let top10 = result["top10"] as? NSDictionary, let items = top10["item"] as? [NSDictionary] { 
    for item in items {
        print(item["count"])
    }
}

它应该可以工作:)

关于arrays - 在 Swift 中反序列化一个以数组作为值的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49676921/

相关文章:

ios - Swift:使表格 View 明显可滚动

python - 在 python 中向嵌套字典添加新值

python - 将列表值附加到字典键

mysql - 在线词典 MySQL 的英文单词

java - 你如何确保用户输入只是整数?

python - 将元组的字符串转换为元组

arrays - Xcode,大量 NsDictionary 消耗了我所有的 RAM

ios - 将 AVCaptureDeviceInput 添加到 CaptureSession 会重置/重新聚焦视频

swift - 如何让 WKWebView 在 macOS 应用程序中快速工作

java - 按列显示数组