Talk:Declarations and Statements (Delphi)
(Redirected from Talk:Declarations and Statements)
Better example of code demonstrating iterating over an enumerable container in Delphi
The example on the help page is misleading. The data is stored in the enumerator class instead of the container! The example below has data into the container (Values in TMyContainer) and has a class to enumerate which only enumerate data in the container.
type TMyIntArray = array of Integer; TMyContainerEnumerator = class; TMyContainer = class public Values: TMyIntArray; function GetEnumerator: TMyContainerEnumerator; end; TMyContainerEnumerator = class Container : TMyContainer; Index : Integer; public constructor Create(AContainer : TMyContainer); function GetCurrent: Integer; function MoveNext: Boolean; property Current: Integer read GetCurrent; end; constructor TMyContainerEnumerator.Create(AContainer : TMyContainer); begin inherited Create; Container := AContainer; Index := - 1; end; function TMyContainerEnumerator.MoveNext: Boolean; begin Result := Index < High(Container.Values); if Result then Inc(Index); end; function TMyContainerEnumerator.GetCurrent: Integer; begin Result := Container.Values[Index]; end; function TMyContainer.GetEnumerator: TMyContainerEnumerator; begin Result := TMyContainerEnumerator.Create(Self); end; var MyContainer : TMyContainer; I : Integer; Counter : Integer; begin MyContainer := TMyContainer.Create; MyContainer.Values := TMyIntArray.Create(100, 200, 300); Counter := 0; for I in MyContainer do Inc(Counter, I); Writeln('Counter = ', Counter, ' (should be 600)'); ReadLn; end.
Response
Thank you, Francois, for your code example. We are evaluating the example and will add it to the docwiki if the team agrees.
Many thanks for your input -
KrisHouser (talk) 16:48, 3 January 2013 (PST)
RS-34754
Example of a For Loop through a set based on an enumerated type
procedure TForm1.Button1Click(Sender: TObject); type Tcol = (cred, cgreen, cblue, cyellow); Tcols = set of Tcol; var Colors: Tcols; col: Tcol; S: string; begin Colors := [cyellow, cblue, cgreen]; S := ''; for Col in Colors do // loop through colors in the set begin case Col of cred: S := S + ' red'; cgreen: S := S + ' green'; cblue: S := S + ' blue'; cyellow: S := S + ' yellow'; end; end; ShowMessage(S); // uses Dialogs end;