我有一个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的定义是说它是ObjectType的KeyPath,所以这里发生了什么?我如何告诉编译器,propertyPath实际上是已更改对象的keyPath。
发布于 2017-11-08 09:24:13
我认为你不应该让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
}
}https://stackoverflow.com/questions/47175231
复制相似问题