Search code examples
swiftswift4kvc

KVC along with associatedtype


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.


Solution

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