I have an generic class A and its subclass B:
class A<T1: Any,T2: Any> {
let x: T1
let y: T2
init (_ v1: T1, _ v2: T2) {
self.x=v1
self.y=v2
}
}
class B<T: Any>: A<T,T> {
init (_ v: T) {
super.init(v,v)
}
}
I need a collection of different objects, all of them belong to subclassess of A:
var arr=[A<Any,Any>]()
But I cannot put objects into the collection, the following code causes an error:
let t=B(10)
arr.append(t as A<Any,Any>)
The error is:
cannot convert value of type 'B' to type 'A' (aka 'A, protocol<>>') in coercion
How to fix this?
Declare t
as B<Any>
(the inferred type by the compiler is B<Int>
):
let t: B<Any> = B(10)
arr.append(t) // works
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With