用不同的键和值解析字典

时间:2016-09-22 14:34:38

标签: swift dictionary

我有这样的字典:

var mapNames: [String: [String]] = 
    [
          "A": ["A1", "A2"],
          "B": ["B1"],
          "C": ["C1", "C2", "C3"]
    ]

现在我有一个第一视图控制器的tableview的功能:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) {

 //I want to print "A", "B", "C" here.

}

在我的第二个视图控制器的tableview'func:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

  //If user taps on "A" in the 1st VC, show here cells with "A1", "A2"

}  

有人可以帮助我解析我的字典首先获取密钥列表然后为每个密钥获取相应值的列表吗?

感谢。

3 个答案:

答案 0 :(得分:0)

要解决此问题,请尝试将Dictionary拆分为Array

示例:

var mapNames: [String: [String]] =
[
    "A": ["A1", "A2"],
    "B": ["B1"],
    "C": ["C1", "C2", "C3"]
]

var mapNamesKeys  = mapNames.keys

var mapNamesValues  = mapNames.values

答案 1 :(得分:0)

正如Eric指出的那样,您应该首先阅读文档。要获得字典的键值,您需要这样做:

for (key, value) in mapNames {
   print(key)
   print(mapNames[key])
}

答案 2 :(得分:0)

要从字典中获取所有密钥,请使用

let keys = mapNames.keys
//keys is the array you need on 1st view controller

现在要获取与每个key对应的数组,请使用

for key in keys
{
    let value = mapNames[key]
    //value is the array you need on 2nd view controller corresponding to the selected key
}