在没有更多上下文的情况下表达式的类型是模棱两可的-CoreBluetooth

时间:2018-11-28 17:23:56

标签: swift class core-bluetooth ambiguous

我有这段代码:

import Foundation
import CoreBluetooth

public class Service {

    static var centralManager: CBCentralManager!

    private init() {}

    public static func doSomething() {
        centralManager = CBCentralManager(delegate: self, queue: nil)
    }

}

但是在构建时,它说我的doSomthing()函数的一行中有错误Type of expression is ambiguous without more context。可能是什么原因造成的?如何使这个小类生成并运行?

1 个答案:

答案 0 :(得分:0)

要成为CBCentralDelegate,您需要a)是NSObject子类,并且b)实际上实现所需的协议方法。您还应该创建一个共享实例,该实例包装了centralManager并仅公开您的界面。

public class Service: NSObject {
    static let shared = Service()
    private lazy var centralManager: CBCentralManager = {
        return CBCentralManager(delegate: self, queue: nil)
    }()

    private override init() {
        super.init()
    }

    public static func doSomething() {
        //Do things with centralManager here
    }
}

extension Service: CBCentralManagerDelegate {
    public func centralManagerDidUpdateState(_ central: CBCentralManager) {
    }
}

呼叫单身人士:

Service.shared.doSomething()