Loop Counter

Get to learn about the foreach loop counter.

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 number with the elements of the range that it is applied on. As a result, the numbers that enumerate generates and the elements of the actual range (NumberRange in this case) appear in lockstep as loop variables:

0: 42
1: 43
2: 44
3: 45
4: 46

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy