Is it necessary to pass a type parameter to static functions in a generic class?
The other answers are correct in their explanations, but you can in fact get the behavior you intuitively expected with this:
extension GenericClass where T == Any {
static func blub(x: Int) -> Int {
return x + 1
}
}
Now this compiles:
let z: Int = GenericClass.blub(x: 4)
Note: Any
is sometimes seen as a code smell. That said, it is the right tool here. The where T == Any
guard here can be interpreted as "for this static function, I don't care what T is, it can be anything", which is what we want.
GenericClass
is not a concrete type in Swift. There's no way to talk about it any more than you can talk about the type Array
without providing its type parameter. (The specific feature Swift lacks that would allow this is called "higher-kinded types.")
Static methods are tied to the concrete type (GenericClass<T>
) not to the higher-kinded type (GenericClass
). In order to access the static methods, it needs to know the actual type you want.
While it's true you're not currently using the type parameter in this class method, there is nothing stopping you (or a subclass!) from doing so. Since you have no way to promise that T
will never occur in this method, there's no way for Swift to allow you to ignore it.