arrays - 追加到深度嵌套数组字典中的数组

标签 arrays swift dictionary append

我在 Swift 中遇到以下问题。首先,我声明一个数据结构,如下所示:

var books = [String : Dictionary<String, Dictionary<String, Dictionary<String, Array<Dictionary<String, String>>>>>]()

我稍后像这样初始化变量:

books = [
    "Fiction" : [
        "Genre Fiction" : [
            "Mystery" : [
                "Classics" : [
                    ["Title" : "Ten Little Indians",
                     "Author" : "Agatha Christie",
                     "read" : "no"],
                    ["Title" : "A Study in Scarlet",
                     "Author" : "Arthur Conan Doyle",
                     "read" : "no"],
                ]
            ]
        ]
    ]
]

请注意,编译器不会对此进行提示。后来,我创建了一个新字典,我想将其 append 到最里面的数组,如下所示:

var bookDict = Dictionary<String, String>()
bookDict = ["title" : dict.valueForKey("title") as! String,
            "author": dict.valueForKey("author") as! String,
            "read"  : dict.valueForKey("read") as! String ]
books["category"]["genre"]["focus"]["set"].append(bookDict)

但是,我收到编译器错误“无法使用类型为 (Dictionary < String, String>) 的参数列表调用追加”。这让我感到困惑,因为 books 数据结构的声明使得最里面的数组是 Dictionary< String, String> 的数组。

我错过了什么?

最佳答案

在编译时并不清楚该键是否确实存在于字典中,因此字典始终返回可选值。您必须检查此选项:

if let category = books["Fiction"] {
    if let genre = category["Genre Fiction"] {
        if let focus = genre["Mystery"] {
            if var set = focus["Classics"] {
                set.append(bookDict)
            }
        }
    }
}

或者你也可以这样做:

books["Fiction"]?["Genre Fiction"]?["Mystery"]?["Classics"]?.append(bookDict)

关于arrays - 追加到深度嵌套数组字典中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32022099/

相关文章:

java - 数组读取问题

swift - nsprintoperation - 检查用户选择了什么

ios - 动态加载一行的选项

python - 使用运行总计创建嵌套字典

python matplotlib : spectrogram plot using pre-computed spectral data array

javascript - 将对象内部的对象数组作为多个对象 JavaScript

Java 二维数组打印问题

python - 将 dict 中的键添加到现有 Pandas 数据框中的列标题

c++ - 如何将<map>存储在<vector>中?