2016-09-22 59 views
1

我有這樣一本字典:解析字典使用不同的密鑰和值

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

現在我有一個第一視圖控制器的實現代碼如下的FUNC:

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

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

} 

在我的第二個視圖控制器的實現代碼如下」 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" 

} 

有人可以幫助我如何解析我的字典先獲取鍵列表,然後爲每個鍵y,獲取相應值的列表?

謝謝。

+1

從源頭瞭解:https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html#//apple_ref/doc/uid/TP40014097-CH8-ID113 – Moritz

回答

0

正如指出的埃裏克,你應該先閱讀文檔。要獲取密鑰 - 一本字典的值,你需要這樣做:

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

爲了解決問題,嘗試將Dictionary分解爲Array

例子:

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

var mapNamesKeys = mapNames.keys 

var mapNamesValues = mapNames.values 
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 
}