Swift:通过索引访问字典

Vin*_*ent 15 indexing dictionary uitableview swift

我想在UITableViewCells中使用字典中的值.我可以通过使用indexPath.row获取值并使用indexPath.section获取字典中的密钥吗?

Fir*_*ras 55

您可以获取密钥数组并获取密钥,indexPath.section如下所示:

Array(yourDictionary.keys)[indexPath.section]
Run Code Online (Sandbox Code Playgroud)

你可以indexPath.row从values数组获取值,如下所示:

Array(yourDictionary.values)[indexPath.row]
Run Code Online (Sandbox Code Playgroud)

编辑:

如果你想获得特定部分键的值,你应该写:

let key = Array(yourDictionary.keys)[indexPath.section]
let array = yourDictionary[key]
let value = array[indexPath.row]
Run Code Online (Sandbox Code Playgroud)


Dun*_*n C 7

字典本质上是无序的.如果您使用dictionary.keys,您可以获得一系列密钥并使用它,正如@Firas在他/她的回答中所说,但不能保证下次获取密钥数组时它们的顺序相同.

另一种选择是使用Int作为键类型,然后使用indexPath.row作为键.

将数组用作表视图的数据源真的更好.

如果要将分段表视图的值存储在字典中,则应使用外部节数组,该数组包含内部行数组,其中包含单元格值的字典.