通用参数'价值'无法推断在swift中创建基于块的KVO

时间:2017-11-03 02:02:02

标签: swift key-value-observing

输入此(人为的示例)代码

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:

的调用出现此错误
  

通用参数'价值'无法推断

目前尚不清楚导致错误的原因。可以采取哪些措施来解决这类问题?

1 个答案:

答案 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,它推断了键路径