Swift array of type [SuperClass] with elements of type [Subclass]

Can someone explain why this code is causing an error?

class Base {}
class SubclassOfBase: Base {}

let baseItems = [Base](count: 1, repeatedValue: Base())
let subclassItems = [SubclassOfBase](count: 3, repeatedValue: SubclassOfBase())

var items = [Base]()
items.append(SubclassOfBase()) //OK
items.appendContentsOf(baseItems) //OK
items.appendContentsOf(subclassItems) //cannot invoke with argument of type [SubclassOfBase]
items.append(subclassItems.first!) //OK

And the next question: the only way to add subclass elements is to add them one by one to the for loop?

+4
source share
1 answer

If you check the headers:

public mutating func append(newElement: Element)

public mutating func appendContentsOf<C : CollectionType where C.Generator.Element == Element>(newElements: C)

Note the difference in type specifiers. While it appendallows you to add something that is Element, that is, includes footers, it appendContentsOfforces you to use an array with exactly the same type of element (subclasses are not allowed).

He will work with:

let subclassItems = [Base](count: 3, repeatedValue: SubclassOfBase())

, , , (, where, ).

:

  • subclassItems.forEach {items.append($0)}
  • ( Array, CollectionType)

    extension Array {
        public mutating func appendContentsOf(newElements: [Element]) {
            newElements.forEach {
                self.append($0)
            }
        }
    }
  • items.appendContentsOf(subclassItems as [Base])
+11

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


All Articles