我想静态地“配置”一个与BLE相关的类,其中包含支持的服务,特性,通知处理程序等,带有typealiases和结构,有点像下面的类。但是,在声明引用该方法的let
常量属性时,Swift编译器不喜欢我引用实例方法的方式(参见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)
}
}
答案 0 :(得分:0)
请注意,错误表明给定的处理程序具有类型
(BleStuff) -> (CharacteristicData, PeripheralName, CharacteristicId) -> Void
不是(CharacteristicData, PeripheralName, CharacteristicId) -> Void
该方法不能单独存在而没有定义的实例来调用它。
如果您有一个在此上下文中使用的实例,则可以将您的行更改为:
private let badCharacteristics = [SupportedCharacteristic.init(id: "1000", handler: handler1(aBLEStuffInstance)]
这是因为methods are curried functions in Swift。
然而,这很好地表明了糟糕的设计。告诉我们您希望实现的目标是有益的。最有可能的是,handler1
应该static
。