www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Why doesn't foreach support iterating?

reply Chris Katko <ckatko gmail.com> writes:
int [50]data;
foreach(i, datum; data){} // works

File file("gasdgasd");
foreach(i, line; file.byLine){} //NOPE.
foreach(line; file.byLine){} //works.

I finally noticed in the docs it says "for arrays only." The 
question is, why?

Every language that I used previously (as far as I can remember) 
implemented foreach in a way that's consistent / orthogonal.

Is there a way around this? Because currently I have to liter my 
foreach's with ugly manual index variables that hold scope even 
after it's gone.

int i = 0;
foreach(line; file.byLine){
//do stuff
i++;
}
i = 2; // still exists!
Oct 16 2018
parent Adam D. Ruppe <destructionator gmail.com> writes:
On Wednesday, 17 October 2018 at 01:17:40 UTC, Chris Katko wrote:
 I finally noticed in the docs it says "for arrays only." The 
 question is, why?
foreach for user-defined types only allow arguments that match what the user defined. Ranges typically do not define this (since it generally doesn't work in all their cases, they may not have an index at all), but you can add it on with an additional call.....
 Is there a way around this?
Add .enumerate to it, see: http://dpldocs.info/experimental-docs/std.range.enumerate.html#examples
Oct 16 2018