Ios 将Swift数组与同一超类合并
我正在试图找到合并Swift数组的最佳方法,这些数组不是相同类型的,但它们具有相同的超类。我已经阅读了所有教程,因此我知道我可以使用:Ios 将Swift数组与同一超类合并,ios,macos,swift,Ios,Macos,Swift,我正在试图找到合并Swift数组的最佳方法,这些数组不是相同类型的,但它们具有相同的超类。我已经阅读了所有教程,因此我知道我可以使用: var array = ["Some", "Array", "of", "Strings"] array += ["Another string", "and one more"] array.append(["Or", "This"]) 在本例中,array变量推断类型[String]。我遇到的问题与类的下一个假设情况有关(在这种情况下,属性并不重要,只是为
var array = ["Some", "Array", "of", "Strings"]
array += ["Another string", "and one more"]
array.append(["Or", "This"])
在本例中,array
变量推断类型[String]
。我遇到的问题与类的下一个假设情况有关(在这种情况下,属性并不重要,只是为了在类之间产生差异):
因此,我创建了一个类A
和B
对象的数组:
var array = [ A(), B(), A(), B() ]
这个数组现在应该是[A]
类型,因为这是A
和B
类的推断类型
现在我想将C
类型的对象附加到此数组中
var-anotherArray=[C(),C(),C()]
由于另一个数组
现在是[C]
类型,我们应该仍然能够追加它,因为所有C
实例都响应A
方法。因此,我们尝试:
array += anotherArray
由于以下原因,此操作失败:
Binary operator '+=' cannot be applied to operands of type '[A]' and '[C]'.
使用append
方法的情况类似。虽然这是有道理的,但我无法理解为什么这不起作用
有人能解释为什么这不起作用吗?这个问题的最佳解决方案是什么?
我找到的唯一明智的解决方案是将另一个数组的类型定义为[A]
,但是否有更好的类型,或者这是正确的
var anotherArray : [A] = [ C(), C(), C() ]
谢谢 如果
C
继承自A
,则可以将[C]
类型的数组“向上转换”为[A]
类型的数组
array += anotherArray as [A]
或者,使用(使用Swift 4测试)
除了Martin的答案之外,您还可以创建一个所有类都符合的协议,然后在创建数组时,将其类型设置为该协议
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]
然后,您可以向其中添加任何类而无需强制转换。您几乎可以合并所有类。唯一的要求是生成的数组的所有元素必须符合相同的协议
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]
或者
var另一个数组:[A]=[C(),C(),C()]
,这样它就知道在数组中使用哪种类型。如果array
具有类型[P]
和另一个数组类型[B]
与协议P
相冲突,那么你也必须向上转换<代码>数组+=另一个数组
未编译。
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]