D features a foreach
loop which allows for
less error-prone and more readable iteration.
Given an array arr
of type int[]
it is possible to
iterate over the elements using a foreach
loop:
foreach (int e; arr) {
writeln(e);
}
The first parameter in a foreach
loop is the variable
name used for each iteration. Its type can be inferred automatically like so:
foreach (e; arr) {
// typeof(e) is int
writeln(e);
}
The second field must be an array - or a special iterable object called a range which will be introduced in the next section.
Elements will be copied from the array or range during iteration.
This is acceptable for basic types, but might be a problem for
large types. To prevent copying or to enable in-place
mutation, ref
can be used:
foreach (ref e; arr) {
e = 10; // overwrite value
}
n
timesD allows us to write iterations which should be executed
n
times, more concisely with the ..
syntax:
foreach (i; 0 .. 3) {
writeln(i);
}
// 0 1 2
The last number in a .. b
is excluded from the range,
thus the loop body is executed 3
times.
For arrays, it's also possible to access a separate index variable.
foreach (i, e; [4, 5, 6]) {
writeln(i, ":", e);
}
// 0:4 1:5 2:6
foreach_reverse
A collection can be iterated in reverse order with
foreach_reverse
:
foreach_reverse (e; [1, 2, 3]) {
writeln(e);
}
// 3 2 1