0

I am looping through an array with the following code:

for leftBlock in leftBlocks {
    // ...
}

I'm doing some comparisons inside of that for-loop, and in some cases I need to remove the current leftBlock from the array. I know how to remove if I have the index, but in this case, I don't.

How do I delete the current object from the array?

1
  • 1
    Use either find or filter Commented Aug 7, 2014 at 19:53

1 Answer 1

1

Use enumerate function which returns a tuple for each value in the array:

for (index,leftBlock) in enumerate(leftBlocks.copy()) {

}

Now you can remove object by its index from original array leftBlocks.

Sign up to request clarification or add additional context in comments.

4 Comments

Is it safe to modify an Array that is bring enumerated in Swift?
@Zaph, thanks, forgot to write copy() for original array. Of course, it is impossible to change array being enumerated.
It is possible but perhaps not safe in Swift, I'm not sure about safe.
@Zaph, obviously it is not a good scheme to implement. The main goal of my post was to show how one can get index in for-in iteration.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.