首页 > 解决方案 > 在 Swift 中使用 int 变量访问字典中的值

问题描述

我正在开发一个 iOS 应用程序,我想使用Array().

我的字典包含一个数组,其中包含结构。

let array = [(key: "S", value: [Thunderbolt.repoStruct(repoName: "Semiak Repo", repoURL: "https://repo.semiak.dev", icon: Optional("iconRound"))]), (key: "T", value: [Thunderbolt.repoStruct(repoName: "Thunderbolt iOS Utilities", repoURL: "https://repo.thunderbolt.semiak.dev", icon: Optional("iconRound"))])]

我正在UITableView使用数组:部分名称是key值,单元格标题是repoStruct.repoName值,并且与以下值相同。

要访问 repoName 我会使用Array(array)[0].1[0].repoName.

问题是我不知道我想要访问的确切位置,而是使用 indexPath 来知道我需要哪个值:

Array(array)[indexPath.section].indexPath.row[0].repoName

这应该返回单元格的 repoName ,而是给我以下错误:Value of tuple type '(key: String, value: [repoStruct])' has no member 'indexPath'

我也尝试过使用:

let row = indexPath.row
Array(array)[indexPath.section].row[0].repoName

但它给了我同样的错误:Value of tuple type '(key: String, value: [repoStruct])' has no member 'row'

我不知道为什么Array(array)[0].1有效并返回值,但Array(array)[indexPath.section].row没有。它做同样的事情:使用位置访问一个值,它是一个 int,例如 indexPath。

我怎么能做到这一点?

提前致谢。

标签: arraysswiftdictionarytuplesnsdictionary

解决方案


强烈建议您不要在数据源数组中使用元组。用额外的结构替换元组

struct Section {
    let name : String
    let items : [Thunderbolt.repoStruct]
}

let array = [Section(name: "S", items: [Thunderbolt.repoStruct(repoName: "Semiak Repo", repoURL: "https://repo.semiak.dev", icon: Optional("iconRound"))], 
             Section(name: "T", items: [Thunderbolt.repoStruct(repoName: "Thunderbolt iOS Utilities", repoURL: "https://repo.thunderbolt.semiak.dev", icon: Optional("iconRound"))]]

并在索引路径获取一个项目

let section = array[indexPath.section]
let item = section.items[indexPath.row]
let name = item.repoName

推荐阅读