openlang

Declaring an array containing constant strings

Is it possible for Delphi to declare a string array using something like the example below?

{'alpha','beta','gamma'}

The conversation continues 4

Follow the reasoning
  1. Permalink

    give this a go

    Const
    EntryCount =4;
    Labels : array [1..EntryCount] of string = ('label1','label2','label3','label4');
  2. Permalink

    You can also use dynamic arrays, as in this example:

    var
      CachedLabels: TArray<string>;
    
    function ReadLabels: TArray<string>;
    begin
      if Length(CachedLabels) = 0 then
        CachedLabels := TArray<string>.Create('Alpha', 'Beta', 'Gamma');
      Result := CachedLabels;
    end;

    Although it initializes a heap-allocated dynamic array at run-time, this demonstrates Delphi's dynamic-array "pseudo-constructor", which permits initialization right where it is used. (NOTE: this example is not thread-safe).

    To obtain the array's length, simply call the standard Length() function, or call the standard Low() and High() functions to determine the valid range of indices.

    For older Delphi versions, substitute your own dynamic string-array type for TArray, for example:

    type
      TLabelArray = array of string;
  3. Permalink

    XE7 lets you define a constant dynamic array as follows:

    const
      Labels: TArray<String> = ['Alpha', 'Beta', 'Gamma'];
  4. Permalink

    There is also an indirect route. Write a function such as:

    procedure copyLabels(var destination: ArrayOfString; const source: Array Of String);
    var
      count, index: Integer;
    begin
      count := Length(source);
      SetLength(destination, count);
      for index := count-1 downto 0 do
        destination[index] := source[index];
    end;

    then invoke that function this way:

    copyLabels(labels, ['LabelA', 'LabelB', 'LabelC']);

    with:

    labels: ArrayOfString;

Other sides of the same question

  1. Choosing enum entries randomly with GDScript in Godot 3.3 without listing each one?

    Here's the enum declaration I'm using in GDScript: I'd like to choose an enum variant randomly without listing every possible…

    Replies 2Latest activity gdscript
  2. Nim remainder syntax

    How is modulus expressed in Nim? cell % 7 == 0 gives undeclared identifier: '%' Neither a Google search nor looking through S…

    Replies 2Latest activity nim
  3. Returning results from an APL function

    How do I make my function return something once execution has finished? For instance, I have: ROUTINE N ? N ⍴ 12 //That gener…

    Replies 2Latest activity apl