KVC 和关联类型

KVC along with associatedtype

我有一个可绑定协议

protocol Bindable: class {
    associatedtype ObjectType: Any
    associatedtype PropertyType

    var boundObject: ObjectType? { get set }
    var propertyPath: WritableKeyPath<ObjectType, PropertyType>? { get set }

    func changeToValue(_ value: PropertyType)
}

我想要一个更改值的默认实现

extension Bindable {

    func changeToValue(_ value: PropertyType) {
        boundObject?[keyPath: propertyPath] = value
    }
}

但这会引发错误:

Type 'Self.ObjectType' has no subscript members

propertyPath 的定义是说它是 ObjectTypeKeyPath 那么这里发生了什么?我如何告诉编译器 propertyPath 确实是更改对象的 keyPath。

我认为您不应该将 propertyPath 设为可选。这应该有效:

protocol Bindable: class {
    associatedtype ObjectType: Any
    associatedtype PropertyType

    var boundObject: ObjectType? { get set }
    var propertyPath: WritableKeyPath<ObjectType, PropertyType>{ get set }

    func changeToValue(_ value: PropertyType)
}

extension Bindable {

    func changeToValue(_ value: PropertyType) {
        boundObject?[keyPath: propertyPath] = value
    }
}