Merge Swift Array with the same superclass

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!

+6
source share
3 answers

If C inherits from A , then you can "scan" an array of type [C] into an array of type [A]

 array += anotherArray as [A] 
+9
source

In addition to Martin's answer, you can create a protocol that matches all classes, and then, when creating an array, make it a type of this protocol.

Then you can add any of the classes to it without casting.

+2
source

you can combine almost everything. the only requirement is that all elements of the resulting array must conform to one protocol.

 let arr1 = [1,2,3] // [Int] let arr2 = [4.0,5.0,6.0] // [Double] let arr3 = ["a","b"] // [String] import Foundation // NSDate let arr4 = [NSDate()] // [NSDate] // the only common protocol in this case is Any var arr:[Any] = [] arr1.forEach { arr.append($0) } arr2.forEach { arr.append($0) } arr3.forEach { arr.append($0) } arr4.forEach { arr.append($0) } print(arr) // [1, 2, 3, 4.0, 5.0, 6.0, "a", "b", 2016-02-15 08:25:03 +0000] 
0
source

Source: https://habr.com/ru/post/986975/


All Articles