我想静态地"配置"与BLE相关的类,带有支持的服务,特征,通知处理程序等,带有Typealiases和structs,有点像下面的类。但是,Swift编译器在声明let
常数属性时不喜欢我引用实例方法的方式(请参阅badCharacteristics
)。做类似此类事情的好方法是什么?必须有一种更迅速的方式来参考实例方法以实现相同的目标。
我考虑过创建一个更削弱的例子,但是我认为一个更真实的示例可能会带来更多的好处。
这是相关编译器错误:Cannot convert value of type to expected argument type
这是代码:
import Foundation
typealias CharacteristicData = NSData
typealias PeripheralName = String?
typealias ServiceId = String
typealias CharacteristicId = String
typealias CharacteristicNotificationHandler = (CharacteristicData, PeripheralName, CharacteristicId) -> Void
private struct SupportedCharacteristic {
let id: CharacteristicId
let handler: CharacteristicNotificationHandler?
}
private struct SupportedService {
let id: ServiceId
let characteristics: [SupportedCharacteristic]
}
class BleStuff: NSObject {
/////// This is what I want to do:
private let badCharacteristics = [SupportedCharacteristic(id: "1000", handler: handler1)]
// ^^^^ Does not compile:
// Cannot convert value of type '(BleStuff) -> (CharacteristicData, PeripheralName, CharacteristicId) -> Void'
// to expected argument type 'CharacteristicNotificationHandler?'
private let badSupportedServices = [SupportedService(id: "2000", characteristics: badCharacteristics)]
////////
// These declarations compile, presumably because handler1 is
// instantiated by the time this runs. But I don't want to do
// it this way...
private var supportedCharacteristics: [SupportedCharacteristic] {
get {
return [SupportedCharacteristic(id: "1000", handler: handler1)]
}
}
private var supportedServices: [SupportedService] {
get {
return [SupportedService(id: "2000", characteristics: supportedCharacteristics)]
}
}
override init() {
super.init()
supportedServices[0].characteristics[0].handler?(NSData(), "one", "two")
}
private func handler1(value: CharacteristicData,
_ peripheralName: PeripheralName,
_ characteristicId: CharacteristicId) -> Void {
print(#function)
}
}
请注意,错误指出其给出的处理程序具有类型
(BleStuff) -> (CharacteristicData, PeripheralName, CharacteristicId) -> Void
不是(CharacteristicData, PeripheralName, CharacteristicId) -> Void
如果没有定义的实例,该方法就无法自行存在。
如果您的实例在此上下文中使用有意义,则可以将行更改为:
private let badCharacteristics = [SupportedCharacteristic.init(id: "1000", handler: handler1(aBLEStuffInstance)]
这起作用是因为方法是迅速中的咖喱功能。
这完全表明了不良设计。告诉我们您希望实现的目标是有益的。最有可能的是,handler1
应该仅制成static
。