类型为[SuperClass]的Swift数组和类型为[Subclass]的元素 [英] Swift array of type [SuperClass] with elements of type [Subclass]
问题描述
有人可以解释为什么此代码引发错误吗?
Can someone explain why this code throws 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
接下来的问题:添加子类元素的唯一方法是在for循环中一个接一个地添加子类元素吗?
And next question: Is the only way to add subclass elements is by adding them one by one in for loop?
推荐答案
如果您检查标头,则:
public mutating func append(newElement: Element)
public mutating func appendContentsOf<C : CollectionType where C.Generator.Element == Element>(newElements: C)
请注意类型说明符之间的差异.虽然 append
使您可以添加 Element
的任何内容,即包括子集,但 appendContentsOf
会强制您使用具有完全相同的数组元素类型(不允许子类).
Note the difference in type specifiers. While append
enables you to add anything that is an Element
, that is, including sublasses, appendContentsOf
forces you to use an array with exactly the same element type (subclasses not allowed).
它适用于:
let subclassItems = [Base](count: 3, repeatedValue: SubclassOfBase())
我认为这是一个错误,因为可以通过改进函数标头轻松解决此问题(嗯,这还需要扩展到 where
子句,因为现在无法检测泛型子类型).
I would consider this to be a bug because this could be easily fixed by improving the function header (well, this also needs an extension to where
clauses because detecting generic subtypes is impossible right now).
一些可能的解决方法:
-
直接为每个项目添加
Append directly for every item
subclassItems.forEach {items.append($0)}
为数组声明一个辅助方法(将对 Array
使用,不适用于通用的 CollectionType
)
Declare a helper method for Arrays (will work for Array
, not for generic CollectionType
)
extension Array {
public mutating func appendContentsOf(newElements: [Element]) {
newElements.forEach {
self.append($0)
}
}
}
直接投射
Direct cast
items.appendContentsOf(subclassItems as [Base])
这篇关于类型为[SuperClass]的Swift数组和类型为[Subclass]的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!