我有这段代码:
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
。造成这种情况的原因是什么?如何使这个小类生成并运行? 最佳答案
要成为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()
关于swift - 在没有更多上下文的情况下表达式的类型是模棱两可的-CoreBluetooth,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53524954/