how can I make a class usable in a foreach statement?
The class contains a associative array (e.g. string[string]). So the foreach statement use this array as source.
So this is what I want:
auto obj = new Obj();
foreach (key, value; obj)
{
...
}
Do I need to implement a interface someting like that?
EDIT:
The solution:
public int opApply(int delegate(ref string, ref Type) dg)
{
int result = 0;
foreach (ref key, ref value; data)
{
result = dg(key, value);
if (result != 0)
{
break;
}
}
return result;
}
Same is done for public int opApply(int delegate(ref Type) dg).
D1:
class Foo
{
uint array[2];
int opApply(int delegate(ref uint) dg)
{
int result = 0;
for (int i = 0; i < array.length; i++)
{
result = dg(array[i]);
if (result)
break;
}
return result;
}
}
D2:
Iteration over struct and class objects can be done with ranges, which means [a set of] properties must be defined:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With