Requiring covariant Self to conform to a protocol

Hello Community,

Say, I have the following code:

class Foo<Bar> {}
protocol FooProtocol {
    func requiredMethod()
protocol ConcreteFooProtocol : FooProtocol {
    func moreConcreteMethodThatCanDeriveRequiredMethod()

extension Foo where Self : ConcreteFooProtocol { // Error 

The compiler will complain:

Covariant 'Self' can only appear as the type of a property, subscript or method result; did you mean 'Foo'?

(no, using Foo instead does not solve that problem)

Can anybody explain to me why this restriction is needed for classes? I was looking for a way to mark the default implementation for requiredMethod in terms of the concrete method as final, but that seems impossible.

Ok, I kind of figured out what could be a problem: if I was able to do the above and mark the method as final, another module could import my module and declare another implementation of the required method on Foo without constraints. Or with different constraints that can be satisfied at the same time. These things would be problem.

Terms of Service

Privacy Policy

Cookie Policy