Swift: 通过下标访问字典

18

我希望在UITableViewCells中使用来自字典的值。我可以通过使用indexPath.row作为值和indexPath.section作为键从字典中获取这些值吗?

4个回答

65

您可以像这样获取键数组并获取 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]

谢谢!我忘了提到,抱歉,我所说的字典看起来像这样:String: [AnyObject],所以每个键有多个对象。是否可能为特定键的值设置一个数组? - Vincent
需要注意的是,字典键返回的顺序未定义,并且可能会在每次调用时更改。因此,您需要将键的数组保存为实例变量,并且应该将其持久化到文件中并读取它(至少在字典内容发生更改之前)。 - Duncan C
似乎数组属性不再可用。但是,这个方法可以:let key = [String](yourDictionary.keys)[indexPath.section] - Ryan H.
这是一个不好的想法。 - Duncan C
@DuncanC 键数组始终具有相同的顺序,您可以进行测试:var dictionary = ["1":1, "2":2, "3":3, "5":5]print(Array(dictionary.keys)) print(Array(dictionary.keys)) print(Array(dictionary.keys)) print(Array(dictionary.keys)) print(Array(dictionary.keys)) print(Array(dictionary.keys)) print(Array(dictionary.keys))dictionary["13"] = 33print(Array(dictionary.keys)) print(Array(dictionary.keys)) print(Array(dictionary.keys)) print(Array(dictionary.keys)) - Firas
显示剩余3条评论

9
字典本质上是无序的。如果你使用dictionary.keys,你可以得到一个键数组并使用它,正如@Firas在他/她的回答中所说,但是不能保证下一次获取键数组时它们会按照相同的顺序排列。
另一个选择是使用Int作为键类型,然后使用indexPath.row作为键。
最好使用数组作为表视图的数据源。
如果你想将分组表视图的值存储在字典中,你应该使用一个外部分组数组,其中包含一个内部行数组,该数组包含单元格的值字典。

4
您可以使用:
Array(yourDictionary)[indexPath.row].key // or .value

0

这是我访问字典索引的小技巧。只需将字典包装起来!

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]]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接