在字典中访问字典

时间:2015-02-18 10:56:02

标签: ios swift dictionary

我有一个字典,其中包含另一个字典:

var channelDict = Dictionary<String, AnyObject>()
channelDict["image"] = Dictionary<String, AnyObject>()

现在我想为子词典添加值,我尝试了以下但没有任何效果:

channelDict["image"]["key"] = "value"

var:Dictionary<String, AnyObject> dict = channelDict["image"]
dict["key"] = "value"

if var dict = channelDict["image"] {
       dict["Key"] = "value"
}

1 个答案:

答案 0 :(得分:2)

这样您就可以在"image"键中添加字典:

channelDict["image"] = ["key": "value"]

<强>已更新

如果你想在内部字典中添加值并保留现有值,你应该像这样创建一个临时变量:

var innerDict = channelDict["image"] as [String: AnyObject]

innerDict["dsa"] = "dsa"

channelDict["image"] = innerDict