使用相同的超类合并Swift数组 [英] Merge Swift Array with same superclass

查看:97
本文介绍了使用相同的超类合并Swift数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到合并Swift数组的最佳方法,它们的类型不同,但它们具有相同的超类。我已经阅读了所有教程,所以我知道我可以使用:

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:

var array = ["Some", "Array", "of", "Strings"]
array += ["Another string", "and one more"]
array.append(["Or", "This"])

在这种情况下,数组变量推断类型 [字符串] 。我遇到的问题与类的下一个假设情况有关(属性在这种情况下并不重要,只是为了区分类):

In this case array variable infers the type [String]. The problem I have relates to the next hypothetical situation with classes (properties do not matter in this case, just there to make a difference between classes):

class A {
    var property1 : String?
}

class B : A {
    var property2: String?
}

class C : A {
    var property3: String?
}

所以我创建了一个类 A的数组 B 对象:

So I create an array of class A and B objects:

var array = [ A(), B(), A(), B() ]

这个数组现在应该是类型 [A] ,因为这是 A B <的推断类型/ code> classes。

This array should now be of type [A], since this is the inferred type by both A and B classes.

现在我想将对象附加到此数组,类型为 C

Now I want to append objects to this array, that are of type C.

var anotherArray = [C(),C(),C()]

由于 anotherArray 现在的类型为 [C] ,我们仍然应该能够附加它,因为所有 C 实例都会响应 A 方法。所以我们尝试:

Since anotherArray is now of type [C], we should still be able to append it, since all C instances respond to A methods. So we try:

array += anotherArray

由于以下原因而失败:

Binary operator '+=' cannot be applied to operands of type '[A]' and '[C]'.

使用追加方法的类似故事。虽然这确实有意义,但我无法理解为什么这不起作用。

Similar story with using append method. While this does make sense, I cannot understand why this couldn't work.

有人可以解释为什么这不起作用吗?这个问题的最佳解决方案是什么?

我找到的唯一明智的解决方案是定义 anotherArray的类型 [A] ,但有没有更好的或这是正确的?

The only sensible solution I found is to define the type of anotherArray to be [A], but are there any better ones or this is correct?

var anotherArray : [A] = [ C(), C(), C() ]

谢谢!

推荐答案

如果 C 继承从 A 然后你可以将 [C] 类型的数组upcast到类型<$ c $的数组中c> [A]

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

array += anotherArray as [A]

这篇关于使用相同的超类合并Swift数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆