【问题标题】:init CBCentralManager: Type of expression is ambiguous without more contextinit CBCentralManager:表达式类型不明确,没有更多上下文
【发布时间】:2019-04-22 08:03:27
【问题描述】:

尝试在 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 时遗漏了一些重要的东西...

我可以在没有委托的情况下使用管理器吗?如果没有,我需要怎么做才能解决错误?

【问题讨论】:

    标签: ios swift core-bluetooth cbcentralmanager


    【解决方案1】:

    这里的诊断具有误导性。问题是你不能在你所在的地方引用selfself 会有类,而不是实例)。

    有几种方法可以解决这个问题,但常见的方法是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,因此对于这种特殊情况,使用! 版本更为常见。

    【讨论】:

    • !version 还在工作吗?我仍然收到错误消息。
    • 如果你的类符合 CBCentralManagerDelegate 委托,错误就会消失。
    猜你喜欢
    • 1970-01-01
    • 2021-05-17
    • 2019-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-30
    • 2019-02-01
    • 1970-01-01
    相关资源
    最近更新 更多