October 17, 2018 Why doesn't foreach support iterating? | ||||
---|---|---|---|---|
| ||||
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! |
October 17, 2018 Re: Why doesn't foreach support iterating? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Chris Katko | 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 |
Copyright © 1999-2021 by the D Language Foundation