在深度嵌套的数组字典中附加到数组
Appending to Array in Deeply Nested Dictionary of Arrays
我在 Swift 中遇到以下问题。首先,我声明一个数据结构,如下所示:
var books = [String : Dictionary<String, Dictionary<String, Dictionary<String, Array<Dictionary<String, String>>>>>]()
我稍后会像这样初始化 var:
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"],
]
]
]
]
]
注意编译器不会抱怨它。后来,我创建了一个新字典,我想将其附加到最里面的数组,如下所示:
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)
但是,我收到 "Cannot invoke append with an argument list of type (Dictionary < String, String>)" 的编译器错误。这让我感到困惑,因为 books 数据结构的声明使得最里面的数组是 Dictionary 的数组。
我错过了什么?
在编译期间不清楚键是否真的存在于字典中,因此字典总是 return 可选值。你必须检查这个选项:
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)
我在 Swift 中遇到以下问题。首先,我声明一个数据结构,如下所示:
var books = [String : Dictionary<String, Dictionary<String, Dictionary<String, Array<Dictionary<String, String>>>>>]()
我稍后会像这样初始化 var:
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"],
]
]
]
]
]
注意编译器不会抱怨它。后来,我创建了一个新字典,我想将其附加到最里面的数组,如下所示:
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)
但是,我收到 "Cannot invoke append with an argument list of type (Dictionary < String, String>)" 的编译器错误。这让我感到困惑,因为 books 数据结构的声明使得最里面的数组是 Dictionary
我错过了什么?
在编译期间不清楚键是否真的存在于字典中,因此字典总是 return 可选值。你必须检查这个选项:
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)