Class 未确认协议 CBPeripheralManagerDelegate

Class does not confirm to Protocol CBPeripheralManagerDelegate

我是 IOS swift 开发的新手,我正在实施一个 class PeripheralHandler,我正在其中初始化 CBPeripheralManager 的一个实例。我已经实现了所需的委托方法,但它仍然显示错误 'Type PeripheralHandler ->() -> PeripheralHandler!' does not confirm to CBPeripheralManagerDelegate.

import Foundation
import CoreBluetooth

class PeripheralHandler : NSObject, CBPeripheralManagerDelegate{

    var myPeripheralManager = CBPeripheralManager(delegate:self, queue: nil)

    func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager!)
    {
        println("peripheralManagerDidUpdateState called !!!")

        switch peripheral.state
        {
        case CBPeripheralManagerState.PoweredOff:
            println("BLE OFF")
        case CBPeripheralManagerState.PoweredOn:
            println("BLE ON")
        case CBPeripheralManagerState.Unknown:
            println("NOT RECOGNIZED")
        case CBPeripheralManagerState.Unsupported:
            println("BLE NOT SUPPORTED")
        case CBPeripheralManagerState.Resetting:
            println("BLE NOT SUPPORTED")
        default:
            println("Error")
        }
    }
}

这是误导性的错误消息。您不能在实例变量的初始赋值中引用 self。当实例变量被实例化时,self 不一定包含任何有意义的东西,所以 Swift 不允许使用 self。

您可以使用惰性变量:

lazy var myPeripheralManager: CBPeripheralManager = {
    return CBPeripheralManager(delegate:self, queue: nil)
}()

当您第一次访问 myPeripheralManager 时将调用此块,它会为您创建对象。