In Swift, when you have a SubType
that inherits from some SuperType
, and there is a GenericType<TypeParameter>
which can accept as its TypeParameter
instances of either class (SubType
or SuperType
), why is it that instances of the GenericType<SubType>
are not convertible to GenericType<SuperType>
?
I have heard that this behavior exists in other languages, and I would expect it to exist in Swift, so I am thirsty for insight here.
class SuperType {
}
class SubType: SuperType {
}
class GenericType<TypeParameter> {
func someGenericFunction() {
print(TypeParameter.self)
}
}
let instance = GenericType<SuperType>()
let subInstance = GenericType<SubType>()
instance.someGenericFunction() // prints "SuperType"
subInstance.someGenericFunction() // prints "SubType"
let array: [GenericType<SuperType>] = [instance, subInstance] // throws error: cannot convert value of type 'SomeGenericClass<SubType>' to expected element type 'SomeGenericClass<SuperType>'