Swift保持对旧数组的引用

时间:2017-06-19 05:51:21

标签: arrays swift

请考虑以下代码:

func arrayEcludingDivingByP (p: Int, arrToCheck : [Int]) -> Array<Int>{

    var  tmp : [Int] = []

    for (ob, index) in arrToCheck.enumerated() {

        var isDividible : Bool = ob % p == 0 ? true : false

        if (!isDividible){
            tmp.append(ob)
        }
    }

    return tmp
}

var p : Int = 2

func getSimpleNumbersArrayFromArray (p : Int, arrPassed : [Int]) -> Array <Int>{

    var tmp : [Int] = []
    tmp = arrPassed

    for i in 0...5 {
        tmp = arrayEcludingDivingByP(p: p+i, arrToCheck: tmp)
        print("tmp array? \(tmp)")

    }
    return tmp


}

arrayEcludingDivingByP函数只返回新数组而没有与特定乘数(p)相乘的项而不进行除法。

getSimpleNumbersArrayFromArray contain loop for 6 iterates, that should output array, which Int objects are not dividible by 0...5 accordingly.

但不知怎的,它始终保持对旧数组的引用,这是1到100之间的数字数组。在控制台中输出如下:

tmp array? [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97]
tmp array? [1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 20, 22, 23, 25, 26, 28, 29, 31, 32, 34, 35, 37, 38, 40, 41, 43, 44, 46, 47]
tmp array? [1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15, 17, 18, 19, 21, 22, 23, 25, 26, 27, 29, 30, 31]
tmp array? [1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 19, 21, 22, 23]
tmp array? [1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17]
tmp array? [1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13]

为什么会这样?它不应该在第二次迭代中包含偶数,但确实如此。

1 个答案:

答案 0 :(得分:2)

你的枚举错了。第一个元素是索引,第二个元素是实际项目(参见here):

for (index, ob) in arrToCheck.enumerated() {
...

那应该可以解决你的问题。