Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift error: cannot convert value of type B to type A in coercion

Tags:

generics

swift

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?

like image 510
Pavel Avatar asked Mar 17 '16 12:03

Pavel


1 Answers

Declare t as B<Any> (the inferred type by the compiler is B<Int>):

let t: B<Any> = B(10)
arr.append(t) // works
like image 100
Ole Begemann Avatar answered Nov 15 '22 07:11

Ole Begemann