【问题标题】:Appending arrays custom function not working附加数组自定义功能不起作用
【发布时间】: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

}

bottombottomExtended 的长度相同。我已使用以下代码成功合并它们:

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


【解决方案1】:

我认为您的问题的原因是您声明的是 CGPoint 数组而不是 CGPoint 数组。

尝试:

var bottom = [CGPoint]()

显然其他数组也是如此

编辑:我不知道为什么这被否决了。如果数组数组是预期的行为,那么它可以正常工作。只是做了一个操场来证明这一点。

显然,您要添加元素的数组是里面的一个方向数组(最后一行代码)。原始底部数组没有被修改,因为方向数组包含底部数组的副本,而不是原始底部数组,因为这条线

directionArray = [right, bottom, left, top]

【讨论】:

    猜你喜欢
    • 2018-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-26
    • 1970-01-01
    • 2016-02-05
    • 2013-02-28
    相关资源
    最近更新 更多