I notice that when I run this code:
var letters = ["a", "b", "c", "d", "e", "f"]
for i in letters {
print(i)
letters.removeLast()
}
it prints:
a
b
c
d
e
f
and not:
a
b
c
I'm assuming it's because when I call removeLast() it's removing from a copy of letters and not the original letters array that the for loop is using. How can I remove from the array the for loop is using?
CodePudding user response:
You're already doing that. Or maybe it's not clear to me what you're trying to do.
When you call removeLast() on an array, it removes the last element from the array. In your code, you are calling removeLast() inside of a for loop. This means that, on each iteration of the for loop, the last element of the array is being removed.
However, a for .. in syntax makes a copy of the array. If you want to access the array directly you could use indicies:
var letters = ["a", "b", "c", "d", "e", "f"]
for (i, letter) in letters.enumerated() {
if (letters.count <= i) {
break
}
print(letter)
letters.remove(at: letters.count - 1)
}
CodePudding user response:
A for loop captures the array being looped over, so even though you are shortening the original array, for is looping over a copy of the original array. This is expected behavior that is explained in detail here.
If you really want to do this, then you need to use a while loop:
var letters = ["a", "b", "c", "d", "e", "f"]
var index = letters.startIndex
while index < letters.endIndex {
print(letters[index])
index = 1
letters.removeLast()
}