我希望在UITableViewCells中使用来自字典的值。我可以通过使用indexPath.row作为值和indexPath.section作为键从字典中获取这些值吗?
我希望在UITableViewCells中使用来自字典的值。我可以通过使用indexPath.row作为值和indexPath.section作为键从字典中获取这些值吗?
您可以像这样获取键数组并获取 indexPath.section
处的键:
Array(yourDictionary.keys)[indexPath.section]
您可以通过以下方式从值数组中获取 indexPath.row
的值:
Array(yourDictionary.values)[indexPath.row]
编辑:
如果你想获取特定部分的键值,应该编写:
let key = Array(yourDictionary.keys)[indexPath.section]
let array = yourDictionary[key]
let value = array[indexPath.row]
Array(yourDictionary)[indexPath.row].key // or .value
这是我访问字典索引的小技巧。只需将字典包装起来!
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]]
let key = [String](yourDictionary.keys)[indexPath.section]
。 - Ryan H.