Zacx Zacx - 16 days ago 6
Swift Question

Swift - nil when unwrapping option value on for loop

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 a fatal error: unexpectedly found nil while unwrapping an Optional value(lldb)
Here is the code I am using,the 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();
}

Answer

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()
}
Comments