swift - 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 类本身中抱怨?
解决方案
您尝试将版本字段添加到产品中,但您还应该在 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]
}
推荐阅读
- unity3d - 更改游戏对象的颜色显示为白色而不是请求的颜色
- c++ - 在 llvm IR 中获取函数的参数名称
- knockout.js - KnockoutJS 如何在数据绑定期间绑定 select 的更改事件而不触发?
- php - 如何检查 IPv6 是否介于 2 个(最小和最大)IPv6 地址的两个范围之间
- android - 按下后退按钮时如何阻止活动重新启动?
- php - 在 laravel 中检索 json 数据时遇到问题
- flutter - MaterialButton onPressed 区域在使用分数平移时被剪裁
- c# - 在我的视图中访问我的推荐中的项目
- java - 在准备好的语句中使用无效表
- c# - 如何在 C# 中随时间减少浮点值?