Swift CollectionView嵌套数组下标访问错误解决方法问询
问题分析与解决
错误原因
- 下标使用错误:你在访问子数组元素时,错误地用
indexPath.row作为子数组的下标。每个子数组(如arrayFirst)仅包含1个元素,正确下标应为0;而indexPath.row是外层嵌套数组的索引,当它的值大于0时,会触发子数组下标越界,同时引发类型匹配错误。 - 多余的类型转换:
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
相关产品推荐
相关产品推荐

