【问题标题】:KVC along with associatedtypeKVC 和关联类型
【发布时间】:2017-11-08 08:52:53
【问题描述】:

我有一个可绑定的协议

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。

【问题讨论】:

    标签: swift swift4 kvc


    【解决方案1】:

    我认为您不应该将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
        }
    }
    

    【讨论】:

    • 你是对的,可选的KeyPath 是个问题。这是一个非常令人困惑的错误。
    • @ViktorKucera:我同意,错误描述很混乱
    猜你喜欢
    • 2011-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多