我在这里弄清楚整个事情有些麻烦。从代码开始:
实体:
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类本身中抱怨呢?
您的ProductRepo
声明缺少对的类型约束Product
。您需要向其添加Entity
约束以使其符合Repository
。
class ProductRepo<Product: Entity> : Repository<Product> {
}
与您的问题无关,但是无需将其Entity
作为类型别名,您只需使其EntityProtocol
符合即可Codable
。另外,对于version
默认实现,由于协议仅需要getter,因此无需添加空的setter。
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]{
[:]
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句