5
votes

I'd like to write a Swift protocol that requires a type to specify a base class and implement methods that operate on subclasses of that base class. Here's what that might look like (doesn't compile):

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 could be specified with a struct type and subclassing wouldn't be allowed. So I tried creating an empty protocol, constrained to classes, to try to inform the compiler that this type will be a class type and allow a subclass constraint.

protocol Model: class { }

Then I constrained the BaseModel type using the Model class protocol:

associatedtype BaseModel: Model

But this generates the same compiler error from above. Is it possible to enforce a subclass constraint from an associatedtype on a protocol? I would expect the above to compile or for Swift to allow something like the following to allow subclass constraints:

associatedtype BaseModel: class

1

1 Answers

0
votes

Associated Types should be used when type is unknown before the protocol is implemented. But if type is known no need to use associated type. I guess you could do this.

protocol Model: class { }

class BaseModel : Model { }

protocol Repository {
        func all<T : BaseModel>(from type: T.Type) -> [T]
}