You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift CollectionView嵌套数组下标访问错误解决方法问询

问题分析与解决

错误原因

  1. 下标使用错误:你在访问子数组元素时,错误地用indexPath.row作为子数组的下标。每个子数组(如arrayFirst)仅包含1个元素,正确下标应为0;而indexPath.row是外层嵌套数组的索引,当它的值大于0时,会触发子数组下标越界,同时引发类型匹配错误。
  2. 多余的类型转换:collectionArrayStr的类型本身就是[[String]],collectionArrayStr[indexPath.row]直接就是[String]类型,不需要用as? [String]做可选绑定,这一步完全冗余。

正确实现代码

var arrayFirst = ["1"]
var arraySecond = ["2"]
var arrayThird = ["3"]
var arrayFourth = ["4"]

var collectionArrayStr = [arrayFirst, arraySecond, arrayThird, arrayFourth]

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return collectionArrayStr.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ViewCell", for: indexPath) as! ViewCell
    
    // 获取当前行对应的子数组
    let currentSubArray = collectionArrayStr[indexPath.row]
    // 子数组仅含一个元素,取下标0的内容
    cell.txtHeading.text = currentSubArray[0]
    
    return cell
}

额外优化建议

如果子数组未来可能包含多个元素,或者想避免下标越界崩溃,可以添加安全判断:

let currentSubArray = collectionArrayStr[indexPath.row]
if let text = currentSubArray.first {
    cell.txtHeading.text = text
} else {
    // 子数组为空时的默认处理
    cell.txtHeading.text = ""
}

内容的提问来源于stack exchange,提问作者Sham Dhiman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 07:15:21