我希望在单个方法中返回任意数量的泛型类的子类,但我不确定如何格式化该函数以便这样做。以下是我的问题的示例游乐场。
class UserViewSet(GenericViewSet):
permission_classes = [AllowAny, ] # or any other permission class
authentication_classes = [JSONWebTokenAuthentication, ] # or any other authentication class
上面的代码不会在游乐场中运行,因为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)
}
,您会看到指向第42行objectToReturn = SubClass.self
的错误。有没有办法更改对象类型以期望泛型的通用和任何子类版本?