输入此(人为的示例)代码
import Foundation
protocol ValueProviderProtocol {
var amount: Int { get }
}
class ValueProvider: NSObject, ValueProviderProtocol {
@objc dynamic var amount = 0
}
let _provider = ValueProvider()
var provider: ValueProviderProtocol { return _provider }
let subject = provider as! NSObject
let observer = subject.observe(\ValueProviderProtocol.amount, options: [.old, .new]) { (provider, changes) in
}
进入Xcode 9游乐场,导致对subject.observe:
的调用出现此错误通用参数'价值'无法推断
目前尚不清楚导致错误的原因。可以采取哪些措施来解决这类问题?
答案 0 :(得分:4)
以下一行:
let observer = subject.observe(\ValueProviderProtocol.amount,
options: [.old, .new])
{ (provider, changes) in
}
需要改为:
let observer = _provider.observe(\.amount,
options: [.old, .new],
changeHandler: { (provider, changes) in
})
您无法尝试观察主题,因为它被下载到没有属性NSObject
的{{1}}。第二个amount
是一个部分键路径,不推断值类型\ValueProviderProtocol.amount
是\.amount
,它推断了键路径