为什么此数组超出索引?

编程入门 行业动态 更新时间:2024-10-22 19:45:37
本文介绍了为什么此数组超出索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图将元素按这种方式构建到二维数组中,但是当代码进入2D数组时,我得到一个错误:数组超出索引。

I am trying to sort elements into a two dimensional array I built this way, but when the code gets to the 2D array I get an error: "array out of index".

var categoryTempArray: [[ProductCatalogue]] = [] func sortinOut(){ var i = 0 var j = 0 for x in categories{ for y in array{ if x == String(stringInterpolationSegment: y.categoryName){ categoryTempArray[i].append(y) //categoryTempArray[i][j] = y tried this too j++ } } i++ }}

推荐答案

您应该先初始化第[i]个元素,然后再附加一些[j]

You should initialize the [i]th element before than appending some [j]th element to it.

您将在不存在的项目上调用append()函数,因为categoryTempArray数组中不存在任何项目,因此索引的边界。

You would call the append() function on an item that does not exist, since no item exists in the categoryTempArray array, thus the index out of bound.

更多推荐

为什么此数组超出索引?

本文发布于:2023-11-29 16:43:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646979.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   索引

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!