运行时出现致命错误(展开时为空)

Fatal error (null when unwrapped) at runtime

我正在将 objective-c 代码转换为 swift,它编译完美,但在运行时出现错误。它说:

fatal error: unexpectedly found nil while unwrapping an Optional value

这是为什么?代码 运行 完全符合 objective-c 格式。

swift版本:

 @IBAction func conn(sender: UIButton) {
         if self.ble.CM.state != CBCentralManagerState.PoweredOn{

         }
         if self.ble.peripherals.count == 0 {
             self.ble.findBLEPeripherals(2)
        }
         else {
             if !(self.ble.activePeripheral != nil) {
                 self.ble.connectPeripheral(self.ble.peripherals.objectAtIndex(0) as! CBPeripheral)
             }
         }

         btnScan.enabled = false


         indConnecting.startAnimating()
     }

此行在运行时抛出错误:

if self.ble.peripherals.count == 0

objective-c版本:

- (void) tryToConnectToBLEShield {
    //Check core bluetooth state
    if (self.ble.CM.state != CBCentralManagerStatePoweredOn)


    //Check if any periphrals
    if (self.ble.peripherals.count == 0)
        [self.ble findBLEPeripherals:2.0];
    else
        if (! self.ble.activePeripheral)
            [self.ble connectPeripheral:[self.ble.peripherals objectAtIndex:0]];


}

实际发生了什么?

我不熟悉该库,但根据您的评论指出 peripherals 是 "for sure" 隐式展开的可选,您需要这样的东西:

if (self.ble.peripherals?.count ?? 0) == 0 {
    self.ble.findPeripherals(2)
}

我们仍然可以使用可选绑定和解包技巧,即使是隐式解包选项。

所以,首先我们使用可选的展开来获取计数:

self.ble.peripherals?.count

如果 peripherals 不是 nil,这将 return peripheralscount,或者 return nil安全。

接下来,我们处理 Nil 合并运算符:

self.ble.peripherals?.count ?? 0

因此,每当左半 returns nil,我们将改为使用 0.

现在我们将其与您尝试做的 0 进行比较:

(self.ble?.peripherals?.count ?? 0) == 0

count0peripheralsnil 时,return true。最终这就是 Objective-C 代码的确切行为,因为方法调用 Objective-C return NULL/NO/0(所有return YES when ==-compared with 0).