5

Given the following enum:

type TEnum = (teA, teB, teC);

I would like to declare a const array of TEnum, however I find with the following the connection between the array items and enum items is relatively hard to read and maintain (obviously I am aware that I can comment verbosely and give each item its own line):

const AN_ARRAY : array[TEnum] of Integer = (1, 12, 146);

Is there a way to declare a const array more like this?

const
  AN_ARRAY : array[TEnum] of Integer : 
    AN_ARRAY[teA] = 1,
    AN_ARRAY[teB] = 12,
    AN_ARRAY[teC] = 146
  ;

Ideally I would like to set the enum ord values and not use the array at all, but this means that I then can't use TypeInfo to manipulate the enum.

Community
  • 1
  • 1
Jamie Kitson
  • 3,973
  • 4
  • 37
  • 50
  • What about `{AN_ARRAY[teA] =} 1,` ? :) I don't think that you can declare a constant array other way than an ordered list of values. – TLama Jun 03 '15 at 16:01

2 Answers2

5

No. The indices of an array constant are always implicit. Include them in comments if you need to see them beside their corresponding values, but beware that the comments may get out of sync with the real code, and the compiler won't warn you about that.

const
  AN_ARRAY : array[TEnum] of Integer = (
    1,  // teA
    12, // teB
    146 // teC
  );
Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
1

This is another approach:

type
  TEnum = (teA, teB, teC);

const
  teAVal = 1;
  teBVal = 12;
  teCVal = 146;

const
  AN_ARRAY : array[TEnum] of Integer = (teAVal, teBVal, teCVal);
Uwe Raabe
  • 45,288
  • 3
  • 82
  • 130
  • Unfortunately there's no guaranteeing the order, is there? – Jamie Kitson Jun 03 '15 at 16:22
  • 2
    Exactly. This introduces complexity while retaining the original problem. -1 – David Heffernan Jun 03 '15 at 16:38
  • 1
    No, Jamie, there is indeed no guaranteeing the order. In this particular example, it's easy to recognize misordered entries because the names of the enum values have an obvious order (A, B, C). On the other hand, it would be hard to recognize a badly ordered list of entries corresponding to the values in [`TRuntimeError`](http://docwiki.embarcadero.com/Libraries/en/System.TRuntimeError), for example. – Rob Kennedy Jun 03 '15 at 16:50