I would like to write a Swift protocol for which you need to specify the type of the base class and implement methods that work with subclasses of this base class. Here's what it looks like (not compiling):
protocol Repository {
associatedtype BaseModel
//T must subclass BaseModel
func all<T: BaseModel>(from type: T.Type) -> [T]
}
But this generates the following compiler error:
Inheritance from non-protocol, non-class type 'Self.BaseModel'
This makes sense, because BaseModel can be specified with the structure type, and the subclass will not be allowed. So I tried to create an empty protocol limited to classes in order to try to tell the compiler that this type would be the type of the class and allow subclass restriction.
protocol Model: class { }
Then I restricted the BaseModel type using the protocol of the Model class:
associatedtype BaseModel: Model
. associatedtype ? , Swift - , :
associatedtype BaseModel: class