Search code examples
delphienumssetdelphi-6

Is the set type suitable for an iteration on a loop?


Have the following enum:

TDays = (tdSunday, tdMonday, tdTuesday, tdWednesday, tdThursday, tdFriday, tdSaturday);

And the following set of that enum:

TChoosenDays = set of TDays;

Now, define the following array:

var
  ArrayStringDaysAcronym : array [TDays] of String = ('SD', 'MD', 'TU', 'WE', 'TH', 'FR', 'ST');

Suppose I have a variable declared as:

var
  Foo: TChoosenDays;
begin
  Foo:= [tdSunday, tdMonday, tdTuesday];

How can I iterate over all members present in the set?

Note: The following doesn't compile, I know I can use array instead of "set of", is it the only way?

function ConcatAcronyms: String;
var
  Item: TDays; 
begin
  Result:= '';
  for Item:= Low(Foo) to High(Foo) do
  begin
    Result:= Result + '; '+ ArrayStringDaysAcronym[Item];
  end;
end;     

Solution

  • Yes. Since you're using D6, you could do it this way:

    function ConcatAcronyms: String;
    var
      Item: TDays;
    begin
      Result:= '';
      for Item:= Low(TDays) to High(TDays) do
      begin
        if Item in Foo then begin
          if Result <> '' then
            Result := Result + ';'  // assuming you don't want Result to start with  a ';'
          Result:= Result + ArrayStringDaysAcronym[Item];
        end;
      end;
    end;