-2

In my swift game i loop through 2 arrays that run every frame(spritekit) like so

      override func update(currentTime: CFTimeInterval) {

        for (i, value) in enumerate(presents) {
          for (ii, pvalue) in enumerate(portals) {

           if(blah == true) {
               presants.removeAtIndex(i)
           }             

           //There is also some code that waits 1 second then runs
           portals.removeAtIndex(ii)


          }
        }
      }

As you can see in the inner loop I sometimes remove. But this sometimes crashes with the error, fatal error: Array index out of range and I am not sure how this is happening. My 2 theories are 1. Since it runs every frame and one has a delay it might be already in the next loop when it is removed OR 2. Since the loop iterates the arrays i am removing from the loop might not reset after it is removed. I could use a try catch( Pure swift no Obj-C ) but all the examples are for throwing errors I want to ignore them.

So my question is: Can I reset the loop or can I implement a try catch in pure swift?

HarveyBrCo
  • 805
  • 1
  • 9
  • 17
  • possible duplicate of [try-catch exceptions in Swift](http://stackoverflow.com/questions/24023112/try-catch-exceptions-in-swift) – holex Nov 22 '14 at 10:18

1 Answers1

1

You are removing items from your collections as you are iterating over them. Don't do that. Instead, you could collect the indices you want to remove in an array, and then remove them in reverse order (from largest to smallest) after you are done with the loops above.

vacawama
  • 150,663
  • 30
  • 266
  • 294