“对于`observe`,无法推断出”通用参数'值'

时间:2017-11-01 19:06:55

标签: ios swift generics key-value-observing

我有一个通用的类,如:

class Row<T> {

    ...

}

如果我的Row实例TExampleClass,我希望能够这样做:

row.bind(to: \ExampleClass.category)

然后在bind我想开始观察我在班级中ExampleClass.category个实例的ExampleClass

我已实施:

func bind<Value>(to targetKeyPath: ReferenceWritableKeyPath<T, Value>) {
    if let model = model as? NSObject {
        model.observe(targetKeyPath, options: [.new ,.old], changeHandler: { _, change in
            Log.info?.msg("Now we have some stuff: \(change)")
        })
    }
}

这给了我错误:Generic parameter 'Value' could not be inferred

怎么可能? T已解决,但为何无法推断Value?它应该来自参数targetKeyPath

可重复编码的完整代码:

class Row<T> {

    let model: T

    init(model: T) {
        self.model = model
    }

    func bind<Value>(to targetKeyPath: ReferenceWritableKeyPath<T, Value>) {
        if let model = model as? NSObject {
            model.observe(targetKeyPath, options: [], changeHandler: { _, _ in

            })
        }
    }

}

我想如何使用上面的示例类:

class Person: NSObject {
    @objc var age: NSNumber?
}

class Book: NSObject {
    @objc var title: String?
}

let row1 = Row(model: Person())
let row2 = Row(model: Book())

row1.bind(to: \Person.age)
row2.bind(to: \Book.title)

1 个答案:

答案 0 :(得分:0)

你可能过度思考了这一点。问题是model只知道是一个NSObject。您可以像这样重现:

class ExampleClass:NSObject {
    @objc dynamic var category = ""
}
let model = NSObject()
model.observe(\ExampleClass.category) { _,_ in }

同样的错误。如果您将model更改为ExampleClass,问题就会消失。