【发布时间】:2016-12-30 12:10:52
【问题描述】:
我的项目中有以下数组:
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)
但它没有合并数组。我检查了数组计数。我该如何解决这个问题?
【问题讨论】:
-
数组是值类型。您附加的不是对底部数组的引用,而是在 directionArray 内复制
-
你的代码能编译吗?这个
directionArray[enumRawValue].count是一个编译错误,因为Int没有count。 -
@MaxPevsner directionArray 的类型为 [[[CGPoint]]]。 Hilarious404,如果您愿意,可以使用 NSArray(引用类型)重写您的代码,但我相信更好地重新考虑任务并编写自定义类或结构,取决于预期的行为。
-
@ShadowOf 如果我将数组更改为 NSArray,我预见到操作数组会出现问题。如果您能向我展示一个自定义类或结构如何解决我的问题的示例,我将不胜感激。
标签: arrays swift swift2 append