【问题标题】:Type of expression is ambiguous without more context - CoreBluetooth没有更多上下文的表达式类型不明确 - CoreBluetooth
【发布时间】:2019-04-30 16:27:53
【问题描述】:

我有这段代码:

import Foundation
import CoreBluetooth

public class Service {

    static var centralManager: CBCentralManager!

    private init() {}

    public static func doSomething() {
        centralManager = CBCentralManager(delegate: self, queue: nil)
    }

}

但是在构建时,它说我的 doSomthing() 函数的一行中有错误 Type of expression is ambiguous without more context。这可能是什么原因,我怎样才能让这个小类构建和运行?

【问题讨论】:

  • 您在类方法中没有self。我想这是主要问题。您可能对单例模式(在 Swift 中通常命名为 sharedInstance/shared)感兴趣。
  • 那么我应该创建另一个类作为 CBCentralManager 的委托类吗?

标签: swift class core-bluetooth ambiguous


【解决方案1】:

要成为 CBCentralDelegate,您需要 a) 成为 NSObject 子类 b) 实际实现所需的协议方法。您还应该创建一个共享实例来包装 centralManager 并仅公开您的接口。

public class Service: NSObject {
    static let shared = Service()
    private lazy var centralManager: CBCentralManager = {
        return CBCentralManager(delegate: self, queue: nil)
    }()

    private override init() {
        super.init()
    }

    public static func doSomething() {
        //Do things with centralManager here
    }
}

extension Service: CBCentralManagerDelegate {
    public func centralManagerDidUpdateState(_ central: CBCentralManager) {
    }
}

调用单例:

Service.shared.doSomething()

【讨论】:

  • 这是有道理的。但我把它写成图书馆/ cocoapod 的一部分,所以当我尝试按照你说的那样调用 doSomething() 时,它告诉我shared is inaccessible due to internal protection level
  • 然后将其设为 public static let shared = Service()
猜你喜欢
  • 1970-01-01
  • 2021-05-17
  • 2019-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-01
  • 2019-04-22
  • 1970-01-01
相关资源
最近更新 更多