Swift开发iOS应用:用indexPath访问字典内结构体数组的问题
解决iOS UITableView中访问元组数组内结构体的问题
嘿,我来帮你搞定这个小问题~ 其实核心是你搞混了元组的访问方式,咱们一步步理清楚:
为什么Array(array)[0].1[0].repoName能正常工作?
你定义的array本身就是一个元组数组,每个元组的结构是(key: String, value: [Thunderbolt.repoStruct])。这里的.1是元组的位置访问语法——元组的第一个元素是.0(对应key),第二个是.1(对应value)。所以Array(array)[0].1其实就是拿到了第一个section对应的repo数组,再用[0]取数组里的第一个结构体,自然能拿到repoName。
你的代码报错的原因
你写的Array(array)[indexPath.section].indexPath.row[0].repoName完全是语法错误:
Array(array)[indexPath.section]拿到的是一个元组,这个元组只有key和value两个成员(或者.0、.1),根本没有indexPath这个属性,所以编译器会报错说“元组没有indexPath成员”。- 后来你用
row变量也是一样的问题,Array(array)[indexPath.section].row是在试图访问元组的row成员,但元组根本没这个东西呀!
正确的实现方式
你需要先从元组里取出value数组,再用indexPath.row去索引这个数组里的结构体。有两种写法都可以:
写法1:用命名成员访问(更清晰推荐)
因为你的元组是带命名的(key: String, value: [repoStruct]),所以直接用.value访问数组,代码可读性更高:
// 在cellForRowAt方法里 let currentSectionData = array[indexPath.section] let currentRepo = currentSectionData.value[indexPath.row] let repoName = currentRepo.repoName
写法2:用位置索引访问
和你之前的.1写法对应,直接用.1取元组的第二个元素:
let repoName = array[indexPath.section].1[indexPath.row].repoName
另外补充个小优化:你定义的array已经是数组类型了,没必要每次都写Array(array),直接用array就行啦~
举个完整的UITableView数据源方法示例:
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return array[section].key // 取section标题 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return array[section].value.count // 每个section的行数 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "YourCellID", for: indexPath) let repo = array[indexPath.section].value[indexPath.row] cell.textLabel?.text = repo.repoName // 如果需要设置其他属性比如图标、URL也可以在这里处理 return cell }
这样就能完美实现你要的:section标题用元组的key,cell标题用结构体的repoName啦~
内容的提问来源于stack exchange,提问作者amodrono
相关产品推荐
相关产品推荐

