Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 将元素插入数组时,数组索引超出范围_Arrays_Swift_Append_Swift3 - Fatal编程技术网

Arrays 将元素插入数组时,数组索引超出范围

Arrays 将元素插入数组时,数组索引超出范围,arrays,swift,append,swift3,Arrays,Swift,Append,Swift3,我有一个数组,其中包含以空开头的UIView(单元格)。当函数通过不同数组循环触发时,我设置它的值: cells = [cell0, cell1, cell2, cell3, cell4] // Code in function ↓ var cellAnimationArray: [NPFCarouselCell] = [] for cell in self.cells { if cell.frame == farLeftFrame { cellAnimationA

我有一个数组,其中包含以空开头的UIView(单元格)。当函数通过不同数组循环触发时,我设置它的值:

cells = [cell0, cell1, cell2, cell3, cell4]

// Code in function ↓

var cellAnimationArray: [NPFCarouselCell] = []

for cell in self.cells {
    if cell.frame == farLeftFrame {
        cellAnimationArray.insert(cell, at: 0)
    } else if cell.frame == leftFrame {
        cellAnimationArray.insert(cell, at: 1)
    } else if cell.frame == centerFrame {
        cellAnimationArray.insert(cell, at: 2)
    } else if cell.frame == rightFrame {
        cellAnimationArray.insert(cell, at: 3)
    } else if cell.frame == farRightFrame {
        cellAnimationArray.insert(cell, at: 4)
    } else {
        print("Frame does not exist!")
        print(cell.frame)
        return
}
当我到达行
cellanimationaray.insert(cell,at:4)
时,应用程序崩溃:

fatal error: Array index out of range

为什么在向数组中插入项目时会出现索引外错误?

在插入足够的元素使
4
成为有效索引之前,您的错误消息会告诉您正在调用
insert(cell,at:4)
。这意味着
self.cells
中项目的顺序是这样的,即您在插入之前在0到3处点击该行。但是不能在4处插入,除非在0到3处已有内容


当您使用已经包含多个项目的数组时,可以避免这种情况,因为索引4已经有效。

在插入足够的元素以使
4
成为有效索引之前,您的错误消息会告诉您正在调用
insert(cell,at:4)
。这意味着
self.cells
中项目的顺序是这样的,即您在插入之前在0到3处点击该行。但是不能在4处插入,除非在0到3处已有内容


当您使用已经包含多个项的数组时,可以避免这种情况,因为索引4已经有效。

@tktsubota。我使用数组的方式必须知道哪个元素在哪里。这就是我使用insert的原因。您可以在索引4处将insert插入到空数组中。它怎么知道用什么填充0…3?@AlexanderMomchliov。问题是,例如,索引3没有分配,所以索引4不存在?使用并行数组存储相关数据是非常脆弱和糟糕的设计。我会考虑设计一个新的设计。我使用数组的方式必须知道哪个元素在哪里。这就是我使用insert的原因。您可以在索引4处将insert插入到空数组中。它怎么知道用什么填充0…3?@AlexanderMomchliov。问题是,例如,索引3没有分配,所以索引4不存在?使用并行数组存储相关数据是非常脆弱和糟糕的设计。我会考虑设计一个新的设计。