Associated type that is a superclass of Self

It would be nice if we could do something like

protocol Foo where Self: SuperClass {
    associatedtype SuperClass: AnyObject
}

But the compiler says Type 'Self' constrained to non-protocol, non-class type 'Self.SuperClass'.

Is there a reason why it does not work? And is there a trick how to make something equivalent possible?

1 Like

This is one of those programming requests where we have to answer: “Your query as-is makes no sense. What do you actually want to do? Then we can respond.”

If conforming types have to be classes, then put AnyObject as (one of) the base protocol(s). If you have a specific base class in mind, put that in the same section as base protocols instead. If you need a specific base class, but the derived type also needs to conform to protocol(s) not part of that base class, then put both the base class and the new protocols in the base protocol section.

If you want the concept of “a class, but not a root class,” that can’t be done AFAIK. Probably because that isn’t actually useful. There is no common interface that all (root) classes must have, so you could never exploit code that would use super.

Terms of Service

Privacy Policy

Cookie Policy