access foreach index counter for Iterate n times

forkit forkit at gmail.com
Sat May 21 01:26:11 UTC 2022


On Saturday, 21 May 2022 at 01:01:40 UTC, mw wrote:
> Not sure if this has been discussed before:
>
> https://tour.dlang.org/tour/en/basics/foreach
>
> ```
> foreach (i, e; [4, 5, 6]) {
>     writeln(i, ":", e);
> }
> // 0:4 1:5 2:6
> ```
>
> so what if I want the loop index counter when I want to loop n 
> times with the .. syntax, I tried:
>
> ```
> foreach (i, e; 5 .. 10) {
>     writeln(i, ":", e);
> }
> ```
>
> right now when I tried it, got syntax error:
>
> onlineapp.d(4): Error: found `..` when expecting `)`
> onlineapp.d(4): Error: found `)` when expecting `;` following 
> statement
>
> Yes, there are a number of manual work-around, but I think the 
> this 2nd foreach loop should be as valid as the 1st one on 
> arrays, so the language behavior is more consistent.
>
> Thoughts?

// ------

module test;
@safe:

import std;

void main()
{
     foreach(i, e; iota(5,11).array)
         writeln(i, ":", e);
}

/+
0:5
1:6
2:7
3:8
4:9
5:10
+/

// ----------------------



More information about the Digitalmars-d mailing list