首页 > 解决方案 > Swift 类型在泛型约束处不符合协议错误,但在类本身不符合

问题描述

我在弄清楚这整件事时遇到了一些麻烦。从代码开始:

实体:

protocol EntityProtocol : class {
    var id: String { get set }
    var version: String { get }
    var deleted: Bool { get set }
    var uid: String { get set }
    func Validate() -> [String: String]
}
extension EntityProtocol {
    var version: String {
        get { return "v0.0" }
        set { }
    }
    func Validate() -> [String: String]{
        //some default checking for default fields
    }
}
typealias Entity = EntityProtocol & Codable

产品:

class Product: Entity {
    var id: String = ""
    var deleted: Bool
    var uid: String = ""

    func Validate() -> [String : String] {
      //implementation
    }
}

到目前为止,编译时没有错误......然后我有class Repository<TEntity> where TEntity: Entity一个实现实际存储库功能的基类......

现在,当我这样做时class ProductRepo<Product> : Repository<Product>,这里显示一个错误,Type 'Product' does not conform to protocol 'EntityProtocol'但是,Product 类本身仍然没有错误。

PS:我尝试将version字段添加到产品中,仍然是同样的错误。我使用带有继承的协议而不是类的原因是 Codable 不能被继承,并且必须自己编写 init 和序列化。

任何人都可以告诉我为什么会发生这种情况以及如何解决它?我很困惑,如果 Product 不符合协议,那么为什么编译器不会在 Product 类本身中抱怨?

标签: swift

解决方案


您尝试将版本字段添加到产品中,但您还应该在 EntityProtocol 协议中创建版本 {get set}然后它将起作用

protocol EntityProtocol : class {
    var id: String { get set }
    var version: String { get }
    var deleted: Bool { get set }
    var uid: String { get set }
    func Validate() -> [String: String]
}

推荐阅读