Mer*_*tio 3 ios core-bluetooth cbcentralmanager swift
尝试在 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) { }
}
Run Code Online (Sandbox Code Playgroud)
如果我self因为nil错误消失而退出,那么我想我错过了一些重要的东西,因为我的一致性CBCentralManagerDelegate......
我可以在没有代表的情况下使用经理吗?如果没有,我需要做什么来解决错误?
这里的诊断具有误导性。问题是你不能self在你所在的地方引用(self会有类,而不是实例)。
有几种方法可以解决这个问题,但一种常见的方法是lazy属性:
lazy var manager: CBCentralManager = {
return CBCentralManager(delegate: self, queue: nil)
}()
Run Code Online (Sandbox Code Playgroud)
另一种方法是一个!变量:
var manager: CBCentralManager!
override init() {
super.init()
manager = CBCentralManager(delegate: self, queue: nil)
}
Run Code Online (Sandbox Code Playgroud)
两者都有点难看,但它们是我们目前在 Swift 中所能做到的最好的。
请记住,该lazy方法在第一次被引用之前根本不会创建 CBCentralManager,因此!在这种特殊情况下使用该版本更为常见。
| 归档时间: |
|
| 查看次数: |
1614 次 |
| 最近记录: |