Best practice for loop iterating in reverse

Swifters,


I'm eliminating for loops that use C-style syntax (initialize; terminate; increment), and I don't know if I'm doing it right for for loops that iterate in reverse (e.g., decrement). For example, I have a for loop over integers where startIndex is greater than endIndex, and iterates downward like this:


for (var i = startIndex - 1; i >= endIndex; --i) {


Is the best practice to use reverse()? For example:


for i in (endIndex...(startIndex - 1)).reverse() {


And if that might be right, this modest optimization:


for i in (endIndex..<startIndex).reverse() {

Thanks in advance!

Replies

I think the best way to do these kind of for loops is to use the stride() function like:


for index in 10.stride(through: 0, by: -2) {
  print(index)
}

The fact that your bounds are namesd as indexes is a bit suspicious. Can you iterate directly?


Keep in mind that you can also reverse a collection:


for value in collection.reverse() {
   ...
}


The reversal is O(1), so it doesn't do any actual copying. It just reverses the order on the fly.

The reversal is O(1)

This is true as you are referring your case is reverse a collection. But in more general point of view, SequenceType also has reverse() method and it's O(N) and always creates a new array. (Which seems to be one reason why `reverse` is being a method than property.) If you do care about efficiency, you need to know which reverse will be applied.

Thanks for all the feedback! OK, so here's my synopsis, for my needs:


  • Using .reverse() is acceptable, as long as it's O(1) which it should be for integers
  • Using .stride(...) is also useful, especially when iterating by more than 1


Yes, I'm iterating over integers, not collections. The word "index" is a common lingo for "I'm going to iterate on this"...