核心蓝牙可选类型不是 CBCentralmanager

Core Bluetooth Optional Type not CBCentralmanager

我正在开发一个包含 CoreBluetooth 的项目。我研究了该主题并在网上找到了一些教程。

现在我重新创建了其中的一些教程,几乎在每一种方法中我都遇到了以下错误:

Initializer for conditional binding must have Optional type, not 'CBCentralManager'

func centralManagerDidUpdateState(central: CBCentralManager) {
    if let central = central{ //Here is the error line
        if central.state == CBCentralManagerState.PoweredOn {
            print("Bluetooth ON")
        }
        else {
            // Can have different conditions for all states if needed - print generic message for now
            print("Bluetooth switched off or not initialized")
        }
    }

}

传递给委托方法的 CBCentralManager 不是可选的 - 它没有 ? 后缀,因此您不需要解包它。这就是错误告诉您的内容 - 您正在尝试解包一个不是可选的变量。

你可以直接说

func centralManagerDidUpdateState(central: CBCentralManager) {
    if central.state == CBCentralManagerState.PoweredOn {
        print("Bluetooth ON")
    }
    else {
        // Can have different conditions for all states if needed - print generic message for now
        print("Bluetooth switched off or not initialized")
    }
}