KVC along with associatedtype

58 Views Asked by At

I have a Bindable protocol

protocol Bindable: class {
    associatedtype ObjectType: Any
    associatedtype PropertyType

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

    func changeToValue(_ value: PropertyType)
}

I want to have a default implementation for changing a value

extension Bindable {

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

But this will throw an error saying:

Type 'Self.ObjectType' has no subscript members

The definition of propertyPath is saying that it's a KeyPath for ObjectType so what's going on here? How can I tell the compiler that propertyPath really is the keyPath for changed object.

1

There are 1 best solutions below

2
Puneet Sharma On BEST ANSWER

I don't think you should make propertyPath optional. This should work:

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
    }
}