Viktor Kucera
Viktor Kucera

Reputation: 6335

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.

Upvotes: 0

Views: 54

Answers (1)

Puneet Sharma
Puneet Sharma

Reputation: 9484

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

Upvotes: 2

Related Questions