I am trying to find a better way to merge Swift arrays that are not of the same type, but they have the same superclass. I already read all the tutorials, so I know that I can use:
var array = ["Some", "Array", "of", "Strings"] array += ["Another string", "and one more"] array.append(["Or", "This"])
In this case, the variable array introduces the type [String] . The problem that I have in connection with the following hypothetical situation with classes (properties do not matter in this case, just to make the difference between classes):
class A { var property1 : String? } class B : A { var property2: String? } class C : A { var property3: String? }
So, I create an array of objects of class A and B :
var array = [ A(), B(), A(), B() ]
This array should now be of type [A] , since it is an inferred type of both classes A and B
Now I want to add objects to this array that are of type C
var anotherArray = [ C(), C(), C() ]
Since anotherArray now of type [C] , we can still add it, since all C instances respond to A methods. Therefore, we try:
array += anotherArray
This fails due to:
Binary operator '+=' cannot be applied to operands of type '[A]' and '[C]'.
A similar story using the append method. Although this makes sense, I donโt understand why it didnโt work.
Can someone explain why this is not working? What is the best solution to this problem?
The only reasonable solution I found was to define anotherArray type as [A] , but are there any better ones, or is this correct?
var anotherArray : [A] = [ C(), C(), C() ]
Thanks!