arrays - 在 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。
我怎么能做到这一点?
提前致谢。
解决方案
强烈建议您不要在数据源数组中使用元组。用额外的结构替换元组
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
推荐阅读
- php - Laravel - Route::resource 和 Route::post - 同时使用
- reactjs - 如何使用 Webpack/SplitChunks 插件按目录动态拆分?
- java - 如何使用 setter 方法更改矩阵(二维数组)中的元素?
- php - Laravel 减少查询
- node.js - 使用邮递员发布多个文档不起作用
- python - 如何解决内存错误问题?
- ionic-framework - 在 Ionic 中成功更新后,MobileFirst 8.0 Direct Update 不更新 UI
- javascript -
返回一个空白页 - ReactJS - android - 在编写 Gradle 依赖项时,我在哪里可以找到要参考的 AndroidX 工件列表?
- json - 如何替换/更新golang中json数组中的键值?