Cannot use original generic in a generic subclass that provides a concrete type for the generic

class BaseClass<T> {
}

class SubClass: BaseClass<Int> {
    var test: Optional<T> = .none
}

This code won't compile. It complains that there is no type T in the subclass scope. Why isn't there support for using generics in subclasses for which a concrete type was provided? This is a problem because if I want to change the type at a later point from say Int to Double, then I would have to scan the class's code base to see what usages of Int resolve to T and which don't. When I could've just used T in the first place where intended, and then if I wanted to change the type to something more specific — maybe something that is everything an Int is but more — then I could've just change the type in the extension definition.

Long story short, you can do what you want by writing:

class BaseClass<T> {
  typealias T = T
}
5 Likes

Generic parameters are lexically scoped. They are introduced by the generic parameter list syntax <T> and remain visible until the end of the declaration's body.

The generic parameters of the subclass are in general completely different than the superclass, so this is valid too for example:

class Base<T> {}
class Derived<T>: Base<Array<T>> {}
4 Likes