Marco Santarossa Marco Santarossa - 1 year ago 44
Swift Question

Swift - Concatenate two array with same superclass

I tried reading this question but doesn't fix my problem.

I have a superclass:

class A {
let date = NSDate()

and two subclasses:

class B: A
class C: A

then two arrays:

var arrayB = [B(), B()]
var arrayC = [C(), C()]

and I want to concatenate in a third array, just for example:

var array = arrayA + arrayB

If I try:

var array = arrayB as! [A]

I have the following error:

'A' is not a subtype of 'B'

What is the right approach?

I fixed with this:

var array = { return $0 as A } { return $0 as A }

but I think it is not the right way.

Let me know in the comment if I was wrong something before downvoting, thanks.

Answer Source

One way:

class A {
    let date = NSDate()

class B : A {

class C : A {


let bList = [B()]
let cList = [C()]

let list = bList as [A] + cList as [A]


let bList: [A] = [B()]
let cList: [A] = [C()]

let list = bList + cList