Why isn't generic inheritance allowed?

Why doesn't this function compile?

func takesSubclass<T: AnyObject, U: T>(_: T, _: U) { }

It gives an error: U constrained to non-protocol, non-class type T, but T is a class. If this is just not allowed, the error message should be improved.

1 Like

in general when you parameterize a type, the type parameter behaves as if it were a “simple” type that cannot itself be used as a constraint.

if you want to say that U:AnyObject, that can be statically type-checked because AnyObject is a type constant. but you can’t require U:T, because T is not known at compile time.


I think I understand; however, the error message doesn't really communicate this very well. It would be better if it was:
U constrained to generic parameter T.

1 Like

The Generics Manifesto amusingly lists this under "minor extensions", but I think it would be quite a big change.

1 Like