Swift Generics - Allow subclasses passed as parameters

Viewed 1318

I'm wondering if it's possible to allow a method to take in any subclass of a generic superclass. I've posted example code of what I'm trying to achieve below. Hopefully that describes my situation a little better.

import UIKit

class SuperDataClass {

}

class SubDataClass: SuperDataClass {

}

class SuperClass<T: SuperDataClass>: UITableViewCell {

}

class SubClass: SuperClass<SubDataClass> {

}

class Example {
    func test(object: SuperClass<SuperDataClass>) {
        print(object)
    }
}

let object = SubClass()
Example().test(object: object)

When running this in a playground you'll get the following error:

Playground execution failed: error: Generics.playground:20:24: error: cannot convert value of type 'SubClass' to expected argument type 'SuperClass<SuperDataClass>'

The reason, as far as I can tell, is that the data type is a subclass of the data type expected by the method.

Changing line 15 to

class SubClass: SuperClass<SuperDataClass> {

Will fix the issue but isn't applicable to the scenario I'm trying to achieve. I'd like the method to treat any object that is subclassing SuperClass to be handled by this one method. Is this possible? Is there a better setup that I should be using in order to achieve this?

Thank you.

2 Answers
Related