Standard Library
interface IIterable<T>
A source of values that can be walked with for.
since 0.1.0-alpha.1linuxwindowswasm
Overview
A type that implements IIterable<T> provides iterator(), which returns a fresh IIterator<T>. for (T x in value) calls it and then hasNext and next until the iterator is exhausted. Arrays, maps and ranges are iterable and are looped over directly with for; implement this interface on your own collections to give them the same loop syntax. Strings are not iterable: loop over s.chars().
Examples
A user-written collection
class Evens : IIterator<int> {
int cur;
int last;
new Evens(int last) { cur = 0; this.last = last; }
bool hasNext() => cur <= last;
int next() {
int v = cur;
cur = cur + 2;
return v;
}
}
class EvenRange : IIterable<int> {
int last;
new EvenRange(int last) { this.last = last; }
IIterator<int> iterator() => Evens(last);
}
EvenRange r = EvenRange(8);
for (int n in r) {
console.writeln(n);
}
0
2
4
6
8
Methods
iterator
iterator() -> IIterator<T>Create an iterator positioned at the first value.
Each call returns a new, independent iterator, so the same collection can be walked more than once.
Returns
A new iterator over the values.
Examples
class TwoWords : IIterator<string> {
int i;
new TwoWords() { i = 0; }
bool hasNext() => i < 2;
string next() {
i = i + 1;
return i == 1 ? "first" : "second";
}
}
class Words : IIterable<string> {
IIterator<string> iterator() => TwoWords();
}
Words w = Words();
IIterator<string> it = w.iterator();
while (it.hasNext()) {
console.writeln(it.next());
}
for (string s in w) {
console.writeln(s.toUpper());
}
first
second
FIRST
SECOND
See also: IIterator
See also
- IIterator — The pull protocol for walking a sequence one value at a time.