简体   繁体   中英

Swift: Inheritance in type parameters

I'm trying to cast an object of a class with a type parameter into an object of the same class with a more generic type parameter, as illustrated in the following Swift code:

class ParameterClassA {
}

class ParameterClassB: ParameterClassA {
}

class WorkingClassA<T> {
}

class WorkingClassB: WorkingClassA<ParameterClassB> {
}

let object1 = WorkingClassB()
let object2: WorkingClassA<ParameterClassA> = object1

Unfortunately, and perhaps as expected, this doesn't work because WorkingClassA<ParameterClassB> cannot be "downcast" into WorkingClassA<ParameterClassA> -- I know Java doesn't allow it, I was hoping Swift might be better able to support such constructs.

Is there a different way to do this is Swift, or is it simply inacceptable? To me it seems fine to "upcast" the type parameter but there might be good reasons not to allow it?

Thanks!

As convenient as this kind of thing could be, it's not really what generics are intended to do.

To the compiler, each generic is of a different Type and is (currently) unrelated to it's sibling generic Types. That means casting WorkingClassA<ParameterClassB> to WorkingClassA<ParameterClassA> is no different than casting WorkingClassA<ParameterClassB> to WorkingClassA<String> or WorkingClassA<Int>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM