我的方法在与协议相关的参数中接收泛型类型。在此方法中,我使用其他NSObject
类来包装/隐藏泛型类型,因为KVO
仅适用于ObjC
类。
下面给出一个例子:
protocol OutputData: NSObjectProtocol {
associatedtype Output
var dataContainer: DataContainer<Output>? { get set }
}
class DataContainer<O>: NSObject {
var outputData: O?
}
func injectResult<O: OutputData>(from: O) {
let dataCont = from.dataContainer
observer = dataCont?.observe(\.outputData) { (object, change) in
let data = object.outputData as! Data
self.inputData = data
}
}
在这种情况下,我没有看到任何编译时错误,但如果我尝试运行此代码,我会得到下一个异常:
Could not extract a String from KeyPath
Swift.ReferenceWritableKeyPath<Concurrency.DataContainer<Foundation.Data>,
Swift.Optional<Foundation.Data>>:
file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-900.0.65.2/src/swift/stdlib/public/SDK/Foundation/NSObject.swift,
line 85
任何帮助将不胜感激。