Jason Tyler Jason Tyler - 4 months ago 26
Swift Question

safely remove item while iterating backward in Swift 3

When I want to pass through and remove an item or items from an array (when certain conditions are met), I typically iterate backward in the C-style for-loop and remove the item by index, avoiding the problem of index numbers being changed of the next item to be processed, or the changing size of the list affecting how many times the loop is passed through. But the C for-loop has been removed in Swift 3.

Here is my Swift 2.3 code for the initialization of the loop:

for (var i = allowedItems.count - 1; i > -1; i -= 1)

Here is the monstrosity created by the Swift 3 converter:

for (i in ((-1 + 1)...allowedItems.count - 1).reversed())

This version does not compile however. ("Expected ',' separator" at the "in" operator).

I simplify the "-1 + 1" bit to zero:

for (i in (0...allowedItems.count - 1).reversed())

Now the error is "Expected Sequence expression for for-each loop".

What is the safe and hopefully reasonably elegant way of iterating backward in Swift 3, in which an index or counter variable is made available for use in specifying which item should be removed? This type of logic appears a number of places in my code so I want to make sure to find the best solution.



Use stride:

for i in stride(from: allowedItems.count - 1, through: 0, by: -1) {