Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through irregular enumeration in Delphi

1) Does anyone know if it is possible to loop through an irregular enumeration in Delphi (XE)?

Looping over a normal enumeration is ok. From Delphi Basics:

var
  suit : (Hearts, Clubs, Diamonds, Spades);
begin
// Loop 3 times
For suit := Hearts to Diamonds do
   ShowMessage('Suit = '+IntToStr(Ord(suit)));
end;

But, if 'suit' instead is declared as

var
  suit : (Hearts=1, Clubs, Diamonds=10, Spades);

it loops 10 times. Not suprising, but I would like to loop 3. The only solution I've found so far is converting an enumeration to a set and use the 'for ... in'-loop like on delphi.about.com.

So, if answer to question 1) is no, then:
2) How to convert from enumeration to set in Delphi?

The context I am using it in is a component array of edit-boxes (TEdit) that has an irregular numbering (edit1, edit5, edit7, edit3, ...). While it is possible to reorder all the edit-boxes, it removes the reason of using enumeration as a flexible way to allow addition of an edit-box in the middle of the enumeration.

like image 686
Truls Avatar asked Nov 09 '10 10:11

Truls


1 Answers

I do not have a Delphi compiler at hand right now, but I tink that gabr's approach can be rather significantly improved by doing

type
  TSuit = (Hearts = 1, Clubs, Diamonds = 10, Spades);

const
  Suits: array[0..3] of TSuit = (Hearts, Clubs, Diamonds, Spades);

Who knows, maybe it doesn't even compile.

like image 140
Andreas Rejbrand Avatar answered Oct 18 '22 02:10

Andreas Rejbrand