我在Obj-C方面很有经验,但对Swift来说还是比较新的。我有一个简单的函数,它将Set和Dictionary作为参数:
TO_DAYS(CURRDATE()) - TO_DAYS(CURRDATE())
传入的参数func buildSource(dataToParse:Set<String>, lookupData:Dictionary<String,AnyObject>) {
for item in dataToParse {
for dict in lookupData {
let nameID = dict["name"] // compile error
}
}
}
是包含嵌套字典的字典。我知道这些字典中的每一个都包含一个名为lookupData
的密钥,但是当我尝试使用以下语法访问该密钥时:
name
我收到以下comile错误:
let nameID = dict["name"]
如果我知道密钥存在,我该如何访问它?谢谢!
答案 0 :(得分:1)
import Foundation
func buildSource(dataToParse:Set<String>, lookupData:Dictionary<String,AnyObject>)->[AnyObject] {
var ret: Array<AnyObject> = []
for item in dataToParse {
for (key, value) in lookupData {
if key == item {
ret.append(value)
}
}
}
return ret
}
let set = Set(["alfa","beta","gama"])
var data: Dictionary<String,AnyObject> = [:]
data["alfa"] = NSNumber(integer: 1)
data["beta"] = NSDate()
data["theta"] = NSString(string: "some string")
let find = buildSource(set, lookupData: data)
dump(find)
/* prints
▿ 2 elements
- [0]: 28 Nov 2015 18:02
▿ [1]: 1 #0
▿ NSNumber: 1
▿ NSValue: 1
- NSObject: 1
*/
代码
for dict in lookupData {
let nameID = dict["name"] // compile error
}
dict不是字典,而是(key,value)元组!
答案 1 :(得分:0)
<强>更新强>
lookupData
获取值"name"
作为key
as? [String:AnyObject]
dataToParse
String
中的dataToParse
访问嵌套字典。func buildSource(dataToParse:Set<String>, lookupData:[String:AnyObject]) {
guard let dict = lookupData["name"] as? [String:AnyObject] else {
return
}
for item in dataToParse {
let value = dict[item]
}
}
更多可能的解决方案:
如果lookupData是一个字典数组:
func buildSource(dataToParse:Set<String>, lookupData:[[String:AnyObject]]) {
for item in dataToParse { // String
for dict in lookupData { // dict
let nameID = dict["name"] // value
}
}
}
如果lookupData是嵌套字典:
func buildSource(dataToParse:Set<String>, lookupData:[String:[String:AnyObject]]) {
for item in dataToParse {
guard let dict = lookupData[item] else {
continue
}
guard let nameID = dict["name"] else {
continue
}
}
}
如果lookupData绝对是[String:AnyObject]
且它的值可能是另一个[String:AnyObject]
,但它可能也不是。{/ p>
func buildSource(dataToParse:Set<String>, lookupData:[String:AnyObject]) {
for item in dataToParse {
guard let dict = lookupData[item] as? [String:AnyObject] else {
continue
}
guard let nameID = dict["name"] else {
continue
}
}
}