2017-06-19 137 views
0

嘗試獲取存儲在數組中的字典的值和密鑰以填充兩個UILabels。Swift 3 - 從字典數組中獲取值

我的數組如下所示:

var fromLocations = [["marco" : "polo"],["jekyll" : "hide"],["freddy" : "jason"]] 

我得到一個集合視圖的indexPath索引。目前嘗試以下內容:

cell.locationName.text = fromLocations[indexPath.item].values[1] 

我試過了一堆其他的方法,但我不能釘它。

回答

1

這是你正在嘗試做什麼?

var fromLocations = [["marco" : "polo1"],["marco" : "polo2"],["marco" : "polo3"]] 
let marco = fromLocations[0]["marco"] 
print("marco = \(marco)") 

這會打印「polo1」。基本上你正在訪問數組中的第一個字典。然後,按照通常訪問字典的方式訪問該字典。

所以一個向下突破是:

let fromLocations = [["marco" : "polo"],["marco" : "polo"],["marco" : "polo"]] 
let theDictionary = fromLocations[0] 
let value = theDictionary["marco"] 

爲了剛剛得到的值與使用密鑰(這是奇怪)數組,把值到一個數組。

var fromLocations = [["marco" : "polo1"],["marco" : "polo2"],["marco" : "polo3"]] 
let marco = Array(fromLocations[0].values)[0] 
print("marco = \(marco)") 

這將打印「polo1」

+0

類,我用佔位符文本顯示字典的數組 - 無論是馬可和馬球會在每一組不同。 – user7684436

+0

啊gotcha。如果您不需要字典密鑰進行訪問,爲什麼不使用字符串數組呢? – kailoon

+0

謝謝 - 我試圖太聰明,我猜字符串數組會好的:) – user7684436