For Each now iterates in index order!

I just noticed in the documentation that For Each now iterates through items by index order (item 1, item 2, etc). This is very useful and lets you eliminate a lot of Ubound code before each For…Next loop.

(I may just be late to the party here; I can’t tell when the change was made. The documentation for For Each used to contain an explicit warning that it did not necessarily go in any particular order.)

1 Like

It has worked that way since For Each was introduced… but was not documented to be guaranteed to do so … until now.

  • Karen
1 Like

Which is why I never depended on it to behave like that. :wink:

1 Like

How does one get the index number?
Is that a stupid question?

1 Like

You would have to track that manually, which is the purpose / benefit of the other kind of loop.

for i as Integer = 0 to ars.LastIndex
  var sThis as String = ars(i)

next i

is functionally equivalent to this:

for each sThis as String in ars
  // sThis is already set up, but you don't know the index

next sThis

However, the later does not have index tracking.

1 Like

As Tim noted, you don’t. It’s a good idea, though, and worth a feature request if it doesn’t already exist. Perhaps something like:

For Each loopIndex as integer, currentItem as SomeClass in myItems
    ...
Next
1 Like

I just discovered this syntax in Python yesterday, and I can’t deny its usefulness. But it would sure look ugly in Xojo. Plus, there are a ton of other syntax improvements I’d rather have first.

3 Likes