An Enumerator has two methods, get the current element (Current) and go to the next element (MoveNext). It does not know about the total state, whats the last element, or go back, etc.
The reason for this is very simple, iterators may be used on non container elements. For example you could have an infinite stream, which has no last element and then you obviously can't reverse it. Another point would be online generators, which generate a new element with each call, so it would be highly inefficient to have to store all previous values.
For example:
{$ModeSwitch advancedrecords}
type
TFibonacciEnumerator = record
First, Second: Integer;
property Current: Integer read Second;
function MoveNext: Boolean;
function GetEnumerator: TFibonacciEnumerator;
end;
function TFibonacciEnumerator.MoveNext: Boolean;
var
tmp: Integer;
begin
tmp := First + Second;
First := Second;
Second := tmp;
Result := Second >= First;
end;
function TFibonacciEnumerator.GetEnumerator: TFibonacciEnumerator;
begin
Result := Self;
end;
function Fibonacci: TFibonacciEnumerator;
begin
Result.First:=0;
Result.Second:=1;
end;
var
i: Integer;
begin
for i in Fibonacci do
WriteLn(i);
end.