我想编写一个Swift协议,要求该类型指定一个基类并实现对该基类的子类进行操作的方法。以下是可能的实现方式(无法编译):
protocol Repository {
associatedtype BaseModel
//T must subclass BaseModel
func all<T: BaseModel>(from type: T.Type) -> [T]
}
但是这会生成以下编译器错误:
Inheritance from non-protocol, non-class type 'Self.BaseModel'
。 这是有道理的,因为BaseModel可以指定为结构体类型,并且不允许子类化。所以我尝试创建一个空协议,并将其约束为类,以尝试告知编译器这种类型将是类类型并允许子类约束。然后,我使用Model类协议对BaseModel类型进行了约束:associatedtype BaseModel: Model
。但是这仍然生成上述相同的编译器错误。是否可能在协议的associatedtype
上强制执行子类约束?我希望上述代码能够编译,或者Swift允许像以下代码那样允许子类约束:associatedtype BaseModel: class
。