0

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>'
eLillie
  • 653
  • 9
  • 17

1 Answers1

0

I'm afraid there is not easy way out... If you want to put both object in an array, you can introduce some protocol which describes the desired behaviour

protocol MyProtocol {
    func someGenericFunction()
}

And then make sure your GenericType conforms to it.

class GenericType<TypeParameter>: MyProtocol {
    func someGenericFunction() {
        print(TypeParameter.self)
    }
}

So.. then you can put your objects in [MyProtocol] array this way:

let instance = GenericType<SuperType>()
let subInstance = GenericType<SubType>()

instance.someGenericFunction() // prints "SuperType"
subInstance.someGenericFunction() // prints "SubType"

let array: [MyProtocol] = [instance, subInstance]
for object in array {
    object.someGenericFunction() // prints "SuperType", "SubType"
}
iWheelBuy
  • 5,470
  • 2
  • 37
  • 71