2

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!")
        print(cell.frame)
        return
}

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?

4
  • @tktsubota. The way I am using the array I have to know which element is where. That is why I am using insert. Commented Aug 16, 2016 at 17:59
  • 2
    You can' insert at index 4 into an empty array. How will it know what to fill 0...3 with? Commented Aug 16, 2016 at 18:00
  • @AlexanderMomchliov. The issue is that, for example, index 3 is not assigned, so index 4 does not exist? Commented Aug 16, 2016 at 18:02
  • 1
    Using parallel arrays to store related data is really fragile and poor design anywy. I would consider architeching a new design. Commented Aug 16, 2016 at 18:05

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.