Thread overview
Implementing Iterator to support foreach
Apr 08, 2015
tcak
Apr 08, 2015
Ali Çehreli
Apr 08, 2015
bearophile
Apr 08, 2015
Rene Zwanenburg
April 08, 2015
I am planning to implement "Iterator" class. But looking at "foreach" statement, it takes a range only.

So is there any way other than returning an array from a function that is to be passed foreach statement? So I could write like that:

Iterator iter = new MyList();

foreach(item; iter){
}


Otherwise I will need to write like that:

foreach(item; iter.getArrayOfAvailableItems()){
}

April 08, 2015
On 04/07/2015 10:59 PM, tcak wrote:
> I am planning to implement "Iterator" class. But looking at "foreach"
> statement, it takes a range only.

The other option is to overload opApply():


http://ddili.org/ders/d.en/foreach_opapply.html#ix_foreach_opapply.opApply

Ali

April 08, 2015
tcak:

> I am planning to implement "Iterator" class. But looking at "foreach" statement, it takes a range only.

Unless you are just experimenting, it's better to not go against a language and its std lib.

Bye,
bearophile
April 08, 2015
On Wednesday, 8 April 2015 at 09:02:08 UTC, bearophile wrote:
> tcak:
>
>> I am planning to implement "Iterator" class. But looking at "foreach" statement, it takes a range only.
>
> Unless you are just experimenting, it's better to not go against a language and its std lib.
>
> Bye,
> bearophile

Also, why do you prefer an iterator over a range?