尝试在 Swift 4.2 项目中初始化 CBCentralManager。
获取评论中显示的错误:
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
...
我可以在没有委托的情况下使用经理吗?如果没有,我需要做什么来解决该错误?
这里的诊断具有误导性。问题是你无法参考self
在你所在的地方(self
会有类,而不是实例)。
有几种方法可以解决这个问题,但常见的方法是lazy
财产:
lazy var manager: CBCentralManager = {
return CBCentralManager(delegate: self, queue: nil)
}()
另一种方法是!
多变的:
var manager: CBCentralManager!
override init() {
super.init()
manager = CBCentralManager(delegate: self, queue: nil)
}
两者都有些丑陋,但它们是我们目前在 Swift 中能做的最好的事情。
请记住,lazy
方法在第一次引用之前根本不会创建 CBCentralManager,因此使用!
此特定情况的版本。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)