Search⌘ K

Loop Counter

Explore how to add loop counters in D foreach loops for user-defined types. Understand how enumerate from std.range works with range member functions and how opApply can be overloaded to support counters. This lesson teaches you to handle iterations safely without mutating collections during loops.

The convenient loop counter of slices is not automatic for other types. Loop counter can be achieved for user-defined types in different ways depending on whether the foreach support is provided by range member functions or by opApply overloads.

Loop counter with range functions

If foreach support is provided by range member functions, then a loop counter can be achieved simply by enumerate from the std.range module:

import std.range; 

// ...

foreach (i, element; NumberRange(42, 47).enumerate) {
    writefln("%s: %s", i, element); 
}

enumerate is a range that produces consecutive numbers starting by default from 0. enumerate pairs each ...