【问题标题】:Swift - nil when unwrapping option value on for loop [duplicate]Swift - 在 for 循环上展开选项值时为零 [重复]
【发布时间】:2017-04-02 10:49:29
【问题描述】:

我正在使用以下代码来删除我游戏中的所有死弹物体,它运行良好,但是在随机时间它会崩溃并用这个致命错误突出显示指示的行:

致命错误:在展开可选值(lldb)时意外发现 nil

这是我正在使用的代码,错误在第 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();
}

【问题讨论】:

  • 这意味着有时Projectile.projs.indexOf(Projectile.deadProjs[i]) 为零并且它崩溃了,因为你用! 强制解包它。解决方案:不要强制解包,使用if let并处理可能的故障。

标签: ios swift


【解决方案1】:

尝试这样做:

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

编辑了 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()
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多