1. Computing

Iterating Over a Set type Variable in Delphi

Using For .. In Set_Values - Looping Through a Set, Enumeration, Range

By

Delphi's set type is one of the features of the language commonly not found in other programming languages. Sets represent a collection of values of the same ordinal type.

A commonly used scenario in Delphi code is to mix both enumerated types and set type.

Here's an example:

 type
   TWorkDay = (Monday, Tuesday, Wednesday, Thursday, Friday) ;
 ...
 const
   FirstShift = [Monday, Wednesday, Friday];
 

Looping Through a Set

If you need to iterate through the elements of a set, you can use the *new* for .. in Delphi loop:
 const
   FirstShift = [Monday, Wednesday, Friday];
   SecondShift = [Tuesday, Thursday];
 var
   aDay : TWorkDay;
 begin
   for aDay in FirstShift do
   begin
     //do something for
     //Monday, Wednesday, Friday
     {once for each element} 
   end
 end;
 
But what if you want to go through every possible value in a set?

Take a look at the next example...

 var
   character : 'a' .. 'z';
 begin
   for character in [Low(character) .. High(character)] do
   begin
     ShowMessage(character) ;
   end;
 end;
 
What will the message display? How many times the message will be displayed?

Answer: the message box will display lower case letters from 'a' to 'z' - 26 characters (English "version")!

Note: Low function returns the smallest available value for a range.
High function returns the upper limit of an Ordinal, Array, or ShortString value.

"Homework" 1:
Let's say you have a label control on a form named "Label1". What will be the result of the code:

 var
   fs : TFontStyle;
 begin
   for fs in [Low(fs) .. High(fs)] do
     Label1.Font.Style := Label1.Font.Style + [fs];
 end;
 
Hint: try it :))

"Homework" 2
Given the next code, what will the message box display?

 type
   TCharSet = set of char;
 var
   character : 'a'..'z';
   charSet : TCharSet;
   phrase : string;
 begin
   charSet := [];
   for character in [Low(character) .. High(character)] do
   begin
     if character in ['d', 'e', 'l', 'p', 'h', 'i'] then
     begin
       Include(charSet, character) ;
     end;
   end;
 
   for character in charSet do
   begin
     phrase := phrase + character;
   end;
 
   ShowMessage(phrase) ;
 end;
 

Answer : "dehilp" :)

Clearing the Confusion: Set, Range, Sub Range, Enumeration

In the above example:
  • "TCharSet" is a character set type - variables of this type can hold character elements - a collection of characters,
  • variable "character" is a subrange variable - can hold any (one) character between (lower-cased) 'a' and 'z',
  • "charSet" is a character set type variable - can hold a collection (set) of any ASCII characters,
  • "word" - is an ordinary string variable.

Delphi tips navigator:
» Implementing OnActivate / OnDeactivate for MDI Child Forms in Delphi - Get Previously Active
« Focus the First Entry Control in a Container

©2014 About.com. All rights reserved.