0

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?

3
  • 1
    The for loop captures the array, even if you remove items from the original array in the loop the loop runs 6 times. Commented Oct 6, 2022 at 8:07
  • Related: stackoverflow.com/q/37997465/1187415 Commented Oct 6, 2022 at 8:12
  • Oh I see. That makes a lot of sense. Thank you for linking that. Commented Oct 6, 2022 at 8:32

2 Answers 2

1

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)
}
Sign up to request clarification or add additional context in comments.

5 Comments

All of the elements are still being printed though. If removeLast() did call why would "d", "e", and "f" still be printing?
@ShayDans have a look at the related link MartinR posted
Oh okay. I just used letters.indices but I ran into an index out of range error since I is still trying to iterate to 6 I believe. I'm going to try what you have here.
It worked! I also copied your if check letter count for I and pasted it in the code using the indices method you told me about and that worked as well. Thank you so much I've been on this for hours. I tried upvoting but I don't have enough reputation lol.
@ShayDans You can still mark the answer as accepted.
0

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()
}

1 Comment

Ohh. Thank you so much for specifying that. I see why while loops are preferred over for loops now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.