Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Foreach on a class

Part of ForeachCategory

Description

You can define how your class iterates through foreach with an opApply method.

Example

import std.stdio;

class Foo {
  uint array[2];

  int opApply(int delegate (inout uint) dg) {
    int result = 0;

    foreach (i, x; array) {
      result = dg(array[i]);
      if (result)
        break;
    }
    return result;
  }
}

void main () {
  Foo a = new Foo;

  a.array[0] = 73;
  a.array[1] = 82;

  foreach (uint x; a) {
    writefln(x);
  }
}