3

I am using the following code to remove all of the dead projectile objects in my game, it works great however at random times it will crash and highlight the indicated line with this fatal error:

fatal error: unexpectedly found nil while unwrapping an Optional value(lldb)

Here is the code I am using, error is on line 4

projs.removeAtIndex(...)

if (Projectile.deadProjs.isEmpty == false && Projectile.projs.isEmpty==false) {
    for i in 0...Projectile.deadProjs.count - 1 {            
        Projectile.projs.removeAtIndex(Projectile.projs.indexOf(Projectile.deadProjs[i])!);
    }
    Projectile.deadProjs.removeAll();
}
FelixSFD
  • 6,052
  • 10
  • 43
  • 117
Zacx
  • 420
  • 5
  • 10
  • 1
    It means that sometimes `Projectile.projs.indexOf(Projectile.deadProjs[i])` is nil and it crashes because you're force unwrapping it with `!`. Solution: don't force unwrap, use `if let` and handle possible failures. – Eric Aya Nov 18 '16 at 14:32

1 Answers1

4

Try to do it this way:

if (Projectile.deadProjs.isEmpty == false && Projectile.projs.isEmpty==false) {
   for i in 0...Projectile.deadProjs.count - 1 {
      if let deadProjIdx = Projectile.projs.indexOf(Projectile.deadProjs[i]) {
         Projectile.projs.removeAtIndex(deadProjIdx);
      }
   }

   Projectile.deadProjs.removeAll();
}

EDITED 2n time: even better:

if !Projectile.deadProjs.isEmpty && !Projectile.projs.isEmpty {
   for deadPrj in Projectile.deadProjs {
      if let deadProjIdx = Projectile.projs.indexOf(deadPrj) {
         Projectile.projs.removeAtIndex(deadProjIdx)
      }
   }

   Projectile.deadProjs.removeAll()
}
Vladyslav Zavalykhatko
  • 15,202
  • 8
  • 65
  • 100