我需要这样的数据,所以我可以将其作为NSDictionary
返回?,请参阅下面的代码
{
"aaa": "a1", //value: String type
"bbb": "b1",
"ccc": "c1",
"ddd": "d1",
"dict2": {
"zzz": "z2", //String type, but sometimes will be nil
"ttt": "t2",
"kkk": null,
"sss": null,
}
}
代码:
let dict2Info = ["zzz":z1, "ttt":t1, "ccc":c1, "kkk":null, "sss":null]
var dict1 = Dictionary<String, AnyObject>()
dict["aaa"] = a1
dict["bbb"] = b1
dict["ccc"] = c1
dict["dict2"] = dict2Info as? AnyObject
println("\(dict1)")
return dict1 //return parameter type is "NSDictionary?"
// result: [aaa: a1, bbb: b1, ccc: c1]
问题:
dict2
丢失(我已检查字典中的key
,dict2
不存在)NSDictionary
?请帮助我!
答案 0 :(得分:3)
var outerDic = [String:Any]()
var innerDic = [String:String?]()
outerDic["aaa"] = "a1"
outerDic["bbb"] = "b1"
outerDic["ccc"] = "c1"
outerDic["ddd"] = "d1"
innerDic["zzz"] = "z2"
innerDic["ttt"] = "t2"
innerDic["kkk"] = nil
innerDic["sss"] = nil
outerDic["dict2"] = innerDic
println(outerDic)
答案 1 :(得分:1)
dict2不缺,你只是没有像字典那样宣称它,而是AnyObject
。
你的错误是在施放dict["dict2"] as? AnyObject
,但是"dict2"
实际上是一个字典。这样做:
dict["dict2"] = dict2Info as? NSDictionary?
请注意,json中的值dict2
是NSDictionary?
的类型,因此您也需要像这样投射它。
也不要忘记将其强制转换为可选(因为nils)。