Caleb Kleveter Caleb Kleveter - 1 year ago 84
Swift Question

Array index out of range when I am inserting an element into the array

I have an array that contains UIViews (cells) that starts empty. I set it's values when a function is fired by looping through a different array:

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!")

When I get to the line
cellAnimationArray.insert(cell, at: 4)
, the app crashes with :

fatal error: Array index out of range

Why am I getting an out of index error when I am insert an item into the array?

Answer Source

Your error message is telling you that you're calling insert(cell, at:4) before inserting enough elements for 4 to be a valid index. Which implies that the order of items in self.cells is such that you're hitting that line before the inserts at 0 through 3. But you can't insert at 4 unless there's already something at 0 through 3.

When you use an array which already contains several items, you avoid this because index 4 is already valid.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download