Mutate array during enumeration

I noticed that enumerating a Swift array gives all elements, even if you mutate the array during the enumeration, for example:

var a = [ 1, 2, 3 ]
for elem in a {
    a.removeAll()
    println(elem)
}
// Output:
// 1
// 2
// 3


Is this something that I can rely upon?

Since for-in uses the generator and it's next() method, the proper question might be: "Does the generate() method of Array capture the array contents?" It seems so, as the following also prints all three original elements:

var a = [ 1, 2, 3 ]
var gen = a.generate()
a.removeAll()
while let elem = gen.next() {
    println(elem)
}

Accepted Reply

Yes, in the same way this code is unaffected by how you change a inside the loop. Both Int and Array are value types, so they are always passed by value.


var a = 3 
for i in 0..<a { 
    a += 1
    print(i) 
}

Replies

You can rely on this, as it is part of array's value semantics.

Yes, in the same way this code is unaffected by how you change a inside the loop. Both Int and Array are value types, so they are always passed by value.


var a = 3 
for i in 0..<a { 
    a += 1
    print(i) 
}

So it seems the old crash occurring when mutating an array while enumerating it is gone for the good... thanks to the value semanthics.