I'm looking to return any number of subclasses of a generic class in a single method but am unsure of how to format the function in order to do so. Below is a sample playground of my issue.
import UIKit
class TableViewCellData {
}
class SubTableViewCellData: TableViewCellData {
}
protocol ClassProtocol {
associatedtype DataType: TableViewCellData
}
class SuperDataClass {
}
class SubDataClass: SuperDataClass {
}
class SuperClass<T: SuperDataClass>: UITableViewCell, ClassProtocol {
typealias DataType = TableViewCellData
}
class SubClass: SuperClass<SubDataClass> {
typealias DataType = SubTableViewCellData
}
class Example {
func test<T: SuperDataClass>(object: SuperClass<T>) {
print(object)
}
func returnType() -> SuperClass<SuperDataClass>.Type? {
var objectToReturn: SuperClass<SuperDataClass>.Type?
if true {
objectToReturn = SuperClass<SuperDataClass>.self
} else {
objectToReturn = SubClass.self
}
return objectToReturn
}
}
let object = SubClass()
Example().test(object: object)
if let object2 = Example().returnType() {
print(object2)
}
The code above will not run in a playground, you will see an error pointing to line 42 objectToReturn = SubClass.self because error: cannot assign value of type 'SubClass.Type' to type 'SuperClass<SuperDataClass>.Type?'. Is there a way to change the object type to expect the generic and any subclass version of the generic?