Marco Santarossa Marco Santarossa - 2 months ago 7
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
and
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 = arrayB.map() { return $0 as A }.arrayC.map() { 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

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]

another:

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

let list = bList + cList
Comments