Swift KVC和关联类型
我有一个可绑定的协议Swift KVC和关联类型,swift,swift4,kvc,Swift,Swift4,Kvc,我有一个可绑定的协议 protocol Bindable: class { associatedtype ObjectType: Any associatedtype PropertyType var boundObject: ObjectType? { get set } var propertyPath: WritableKeyPath<ObjectType, PropertyType>? { get set } func change
protocol Bindable: class {
associatedtype ObjectType: Any
associatedtype PropertyType
var boundObject: ObjectType? { get set }
var propertyPath: WritableKeyPath<ObjectType, PropertyType>? { get set }
func changeToValue(_ value: PropertyType)
}
但这将抛出一个错误,即:
类型“Self.ObjectType”没有下标成员
propertyPath
的定义是说它是ObjectType
的KeyPath
,那么这里发生了什么?如何告诉编译器propertyPath确实是已更改对象的关键路径。我认为您不应该将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
}
}
协议可绑定:类{
associatedtype对象类型:任意
associatedtype属性类型
var boundObject:ObjectType?{get set}
var propertyPath:WritableKeyPath{get set}
func changeToValue(value:PropertyType)
}
可扩展绑定{
func changeToValue(value:PropertyType){
boundObject?[keyPath: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
}
}
协议可绑定:类{
associatedtype对象类型:任意
associatedtype属性类型
var boundObject:ObjectType?{get set}
var propertyPath:WritableKeyPath{get set}
func changeToValue(value:PropertyType)
}
可扩展绑定{
func changeToValue(value:PropertyType){
boundObject?[keyPath:propertyPath]=值
}
}
你是对的,可选的键路径是个问题。这是一个非常令人困惑的错误。@ViktorKucera:我同意,错误描述非常令人困惑您是对的,可选的KeyPath
是一个问题。这是一个非常令人困惑的错误。@ViktorKucera:我同意,错误描述非常令人困惑