Being dim #1: Array and set enumerators

One of my favourite additions to Delphi over the past years has been the for..in construct and the associated enumerators. I just love the way we can do

var
  Ch: Char;
  S: string;
begin
  S := 'Some text';
  for Ch in S do
    // Do something with Ch
end;

So how come I missed that enumerators work on sets and arrays? I'm mentioning this here just in case it's slipped past anyone else, and in case you can tell me about any other enumerators I might have missed!

Since forever I've being having to do stuff like this for arrays and sets:

const
  cMyArray: array[1..4] of Byte = (51, 60, 80, 81);
  cMySet: set of Byte = [50, 51, 80, 81, 40, 30, 32];
var
  I: Integer;
  B: Byte;
begin
  for B := Low(Byte) to High(Byte) do
    if B in cMySet then
      // Do stuff with B
  for I := Low(cMyArray) to High(cMyArray) do
    // Do stuff my cMyArray[I]
end;

When all along I could have been doing:

const
  cMyArray: array[1..4] of Byte = (51, 60, 80, 81);
  cMySet: set of Byte = [50, 51, 80, 81, 40, 30, 32];
var
  Item: Byte;
begin
  for Item in cMySet do
    // Do stuff with Item
  for Item in cMyArray do
    // Do stuff with Item
end;

Duh! A refactoring I will go!

Comments

Popular posts from this blog

Initialising dynamic arrays

Deleting elements from a dynamic array

New String Property Editor Planned For RAD Studio 12 Yukon 🤞