iOS Swift:致命错误:索引超出范围 [英] iOS Swift : fatal error: Index out of range
本文介绍了iOS Swift:致命错误:索引超出范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试删除索引处的对象,但出现错误.这是我的代码:
I'm trying to remove an object at an index but I'm getting an error. Here is my code:
var arr2 = [3,5,6]
let arr3 = arr2
for (index, element) in arr3.enumerated() {
print("III \(index)")
arr2.remove(at: index)
}
日志:
III 0
III 1
III 2
fatal error: Index out of range
请让我知道我在做错什么.
Please let me know what I'm doing wrong.
推荐答案
您的index
值基于arr3
.当您从arr2
中删除项目时,index
并不代表arr2
中的正确位置.
Your index
value is based on arr3
. As you remove items from arr2
that index
doesn't represent the proper location in arr2
.
一种解决方案是反向迭代arr3
.
One solution is to iterate arr3
in reverse.
for (index, element) in arr3.enumerated().reversed() {
这使其余索引与迭代继续相同.
This keeps the remaining indexes the same as the iteration continues.
这篇关于iOS Swift:致命错误:索引超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文