init CBCentralManager:表达式类型不明确,没有更多上下文 [英] init CBCentralManager: Type of expression is ambiguous without more context
问题描述
尝试在Swift 4.2项目中初始化CBCentralManager。
得到注释中显示的错误:
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) { }
}
如果我将 self
换为 nil
,错误消失了,所以我想我是我从符合 CBCentralManagerDelegate
...
If I switch self
out for nil
the error goes away, so I think I'm missing something important from my conformance to CBCentralManagerDelegate
...
我的重要事项中遗漏了一些重要内容代表;如果不是,该怎么办才能解决该错误?
推荐答案
此处的诊断有误导性。问题是您不能在您所在的位置引用 self
( self
会有类,而不是
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).
有几种方法可以解决此问题,但是常见的方法是 lazy
属性:
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)
}()
另一种方法是!
变量:
var manager: CBCentralManager!
override init() {
super.init()
manager = CBCentralManager(delegate: self, queue: nil)
}
两者都很丑陋,但是它们是我们目前在Swift中能做到的最好的事情。
Both are somewhat ugly, but they're about the best we can do in Swift currently.
请记住, lazy
方法在第一次被引用之前根本不会创建CBCentralManager,因此使用<$更为常见。 c $ c>!版本。
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.
这篇关于init CBCentralManager:表达式类型不明确,没有更多上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!