Swift,不同类型的嵌套字典

时间:2015-05-15 07:27:18

标签: ios swift dictionary

我需要这样的数据,所以我可以将其作为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]

问题:

  1. dict2丢失(我已检查字典中的keydict2不存在)
  2. 需要返回NSDictionary
  3. 请帮助我!

2 个答案:

答案 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中的值dict2NSDictionary?的类型,因此您也需要像这样投射它。

也不要忘记将其强制转换为可选(因为nils)。