我有一个Bindable协议
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
}
}
但这会引发错误说:
类型'Self.ObjectType'没有下标成员
propertyPath
的定义是说KeyPath
是ObjectType
所以这里发生了什么?如何告诉编译器propertyPath确实是更改对象的keyPath。
答案 0 :(得分:2)
我认为你不应该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
}
}