我的项目中有以下数组:
var bottom = [[CGPoint]]() // bottom = [bottom1,...,bottom5]
var left = [[CGPoint]]() // left = [left1,...,left5]
var top = [[CGPoint]]() // top = [top1,..., top5]
var right = [[CGPoint]]() // right = [right1,...,right5]
var bottomExtended = [[CGPoint]]()
directionArray = [right, bottom, left, top]
enum Direction: Int {
case right = 0, bottom, left, top
}
bottom
和 bottomExtended
的长度相同。我使用以下代码成功合并了它们:
for i in 0..<bottom.count {
bottom[i].appendContentsOf(bottomExtended[i])
}
我写了一个合并数组的通用函数:
func addToDirectionArray (direction:Direction, addArray:[[CGPoint]]) {
let enumRawValue = direction.rawValue
for i in 0..<directionArray[enumRawValue].count {
directionArray[enumRawValue][i].appendContentsOf(addArray[i])
}
}
我用以下方法测试了它:
addToDirectionArray(.bottom, addArray: bottomExtended)
但它并没有合并数组。我检查了数组计数。我该如何解决这个问题?
最佳答案
我认为您出现问题的原因是您声明的是 CGPoint 数组的数组而不是 CGPoint 数组。
尝试:
var bottom = [CGPoint]()
显然对于其他数组也是如此
编辑:我不知道为什么这被否决了。如果数组的数组是预期的行为,那么它就可以正常工作。刚刚做了一个 Playground 来证明这一点。
显然,您要将元素 append 到的数组是 directionArray 内部的数组(代码的最后一行)。原来的bottom数组没有被修改,因为directionArray包含了bottom数组的COPY,而不是原来的bottom数组,因为这一行
directionArray = [right, bottom, left, top]
关于arrays - 追加数组自定义函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39104989/