![](/img/trans.png)
[英]Swift Generic Implementation of protocol throws error `Type does not conform to protocol`
[英]Swift type does not conform to protocol error at generic constraint but not at class itself
我在弄清楚这整件事时遇到了一些麻烦。 从代码开始:
实体:
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 ...
现在,当我执行class ProductRepo<Product>: Repository<Product>
时,它在此处显示错误,说Type 'Product' does not conform to protocol 'EntityProtocol'
但是,产品 class 本身仍然没有错误。
PS:我尝试将version
字段添加到产品中,仍然是同样的错误。 我使用协议不是 class 和 inheritance 的原因是 Codable 不能被继承,必须自己编写 init 和序列化。
任何人都可以告诉我为什么会发生这种情况以及如何解决它? 我很困惑,如果产品不符合协议,那么为什么编译器不会在产品 class 本身中抱怨?
您尝试将版本字段添加到产品中,但您还应该在 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]
}
您的ProductRepo
声明缺少对Product
的类型约束。 您需要向其添加Entity
约束以使其符合Repository
。
class ProductRepo<Product: Entity> : Repository<Product> {
}
与您的问题无关,但不需要将Entity
作为类型别名,您可以简单地使EntityProtocol
符合Codable
。 此外,对于version
默认实现,不需要添加一个空的 setter,因为协议只需要一个 getter。
protocol Entity: class, Codable {
var id: String { get set }
var version: String { get }
var deleted: Bool { get set }
var uid: String { get set }
func validate() -> [String: String]
}
extension Entity {
var version: String {
"v0.0"
}
func validate() -> [String: String]{
[:]
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.