Sen-He Lee
Sen-He Lee

Reputation: 144

Swift, nested dictionary with different type

I need to have my data like this, so I can return it as NSDictionary?, please refer to my code below

{
    "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,
    }
}

code:

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]

problem:

  1. dict2 is missing (I have checked the key in dictionary, dict2 is not exist)
  2. need to return NSDictionary?

Please help me!

Upvotes: 0

Views: 385

Answers (2)

gutenmorgenuhu
gutenmorgenuhu

Reputation: 2362

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)

Upvotes: 3

Dejan Skledar
Dejan Skledar

Reputation: 11435

The dict2 isnt missing, you just havent declared it like a dictionary, but as AnyObject.

Your mistake is at casting the dict["dict2"] as? AnyObject, but tje "dict2" is actually a Dictionary. Do it like this:

dict["dict2"] = dict2Info as? NSDictionary?

Note that the value dict2 in the json is type of NSDictionary? so you need to cast it like this too.

Also dont forget to cast it as optional (because of nils).

Upvotes: 1

Related Questions