Swift: dictionary access via index

﹥>﹥吖頭↗ 提交于 2020-01-01 01:48:08

问题


I want to use values from a dictionary in my UITableViewCells. Can I get those from a dictionary by using indexPath.row for the value and indexPath.section for the key?


回答1:


you can get the keys array and get the key at indexPath.section like this:

Array(yourDictionary.keys)[indexPath.section]

and you can get the value at indexPath.row from the values array like this:

Array(yourDictionary.values)[indexPath.row]

Edit:

if you want to get the values of a specific section key you should write:

let key = Array(yourDictionary.keys)[indexPath.section]
let array = yourDictionary[key]
let value = array[indexPath.row]



回答2:


Dictionaries are inherently unordered. If you use dictionary.keys, you can get an array of keys and use that, as @Firas says in his/her answer, but there's no guarantee that next time you fetch an array of keys they will be in the same order.

Another option would be to use Int as the key type, then use the indexPath.row as the key.

It's really better to use an array as a data source for a table view.

If you want to store the values for a sectioned table view in a dictionary you should use an outer section array, which contains an inner row array, which contains a dictionary of values for the cell.




回答3:


Here is my small trick to access Dictionary by index. Just wrap dictionary!

var dict = [String: [Int]]()

dict.updateValue([1, 2, 3], forKey: "firstKey")
dict.updateValue([3, 4, 5], forKey: "secondKey")

var keyIndex = ["firstKey": "firstKey", "secondKey": "secondKey"]
var arr = [[String: [Int]]]()

for (key, value) in dict {
    arr.append([keyIndex[key]!: value])
}

print(arr[0]) // ["firstKey": [1, 2, 3]]


来源:https://stackoverflow.com/questions/31775724/swift-dictionary-access-via-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!