Bright Future Bright Future - 2 months ago 8
Swift Question

How to create a new array with arrays of different classes

I have 2 classes, both are subclass of

SuperClass
:

class A: SuperClass {
...
static let arrayA: [A] = [a, b, c]
}

class B: SuperClass {
...
static let arrayB: [B] = [1, 2, 3]
}


Then I want to create a new array of type
SuperClass
:

let newArray: [SuperClass] = A.arrayA + B.arrayB



Here I got an error: type of expression is ambiguous without more context


How can I resolve this?

Answer

Just Posting something i tried on my desk:

class User:NSObject{
    var name: String
    var age: Int

    init(n:String, a:Int) {
        self.name = n
        self.age = a
    }
}

class Section: User {
    static let arrayA: [Section] = [Section(n: "John", a: 20), Section(n: "Mariah", a: 18)]
}

class Library: User {
    static let arrayB: [Library] = [Library(n: "Martin", a: 20), Library(n: "Mariah", a: 18)]
}

Finally:

let newArray:[User] = Section.arrayA.map { $0 as User } + Library.arrayB.map { $0 as User }
print(newArray)

Output:

(lldb) po newArray
▿ 4 elements
  - [0] : <TestSwift2.Section: 0x7fdb4b43d460>
  - [1] : <TestSwift2.Section: 0x7fdb4b43d4e0>
  - [2] : <TestSwift2.Library: 0x7fdb4b43e4b0>
  - [3] : <TestSwift2.Library: 0x7fdb4b43e4e0>

(lldb) po newArray[0].age
20

(lldb) po newArray[0].name
"John"