斯威夫特 - 展开对循环
问题描述:
我使用下面的代码删除所有在我的游戏死人抛射物的期权价值时为零,它在随机时间的伟大工程,但它会崩溃,并强调这种致命的错误指示线:斯威夫特 - 展开对循环
fatal error: unexpectedly found nil while unwrapping an Optional value(lldb)
这里是我使用的代码,错误是在第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();
}
答
尝试做这样:
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时间: 甚至更好:
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()
}
这意味着有时候'Projectile.projs.indexOf(Projectile.deadProjs [1])'是零,它崩溃,因为你力'展开了! '。解决方案:不要强制解包,使用'if let'并处理可能的失败。 – Moritz