Merge Swift Array with same superclass

前端 未结 3 1568
一个人的身影
一个人的身影 2020-12-19 08:25

I\'m trying to find the best way to merge Swift arrays, that are not of same type, but they have same superclass. I\'ve already read all the tutorials so I know I can use:

相关标签:
3条回答
  • 2020-12-19 08:52

    In addition to Martin's answer, you could create a protocol that all of the classes conform to and then when creating your array, make it's type that protocol.

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

    0 讨论(0)
  • 2020-12-19 08:59

    you can merge almost everything. the only requirement is that all elements of resulting array must conform to the same 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 讨论(0)
  • 2020-12-19 09:02

    If C inherits from A then you can "upcast" an array of type [C] to an array of type [A]

    array += anotherArray as [A]
    

    Alternatively, use (tested with Swift 4)

    array.append(contentsOf: anotherArray)
    
    0 讨论(0)
提交回复
热议问题