init CBCentralManager: Type of expression is ambiguous without more context

我与影子孤独终老i 提交于 2020-01-24 14:37:26

问题


Trying to initialize a CBCentralManager in a Swift 4.2 project. Get the error shown in comment:

import CoreBluetooth

class SomeClass: NSObject, CBCentralManagerDelegate {

    // Type of expression is ambiguous without more context
    let manager: CBCentralManager = CBCentralManager(delegate: self, queue: nil)

    // MARK: - Functions: CBCentralManagerDelegate

    func centralManagerDidUpdateState(_ central: CBCentralManager) { }
}

If I switch self out for nil the error goes away, so I think I'm missing something important from my conformance to CBCentralManagerDelegate...

Can I use the manager without a delegate; and if not, what do I need to do to resolve the error?


回答1:


The diagnostic here is misleading. The problem is you can't refer to self in the place you are (self there would be the class, not the instance).

There are a few ways to solve this, but a common way is a lazy property:

lazy var manager: CBCentralManager = {
    return CBCentralManager(delegate: self, queue: nil)
}()

The other approach is a ! variable:

var manager: CBCentralManager!

override init() {
    super.init()
    manager = CBCentralManager(delegate: self, queue: nil)
}

Both are somewhat ugly, but they're about the best we can do in Swift currently.

Remember that the lazy approach won't create the CBCentralManager at all until the first time it's referenced, so it's a bit more common to use the ! version for this particular case.



来源:https://stackoverflow.com/questions/53383490/init-cbcentralmanager-type-of-expression-is-ambiguous-without-more-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!