我正在將一個Objective-C代碼轉換爲swift,它編譯完美,但在運行時給我提供了錯誤。它說:在運行時發生致命錯誤(null時解包)
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]];
}
什麼是實際發生的?
其中之一是隱式解包可選(無論是'ble'還是'peripherals')。在Objective-C中,發送消息到'nil'不是問題。在Swift中,它是。 – nhgrif
我該如何解決? '外設'是肯定的。 –