I have a function in my application that needs to return an array. I have found in a couple of places how to do this by declaring the array type, e.g.
type TStringArray = array of string;
And then declaring my function
function SomeFunction(SomeParam: Integer): TStringArray;
My problem is trying to set this up in a form that has both interface and implementation. How do I declare my type and have a function declaration with that type in the interface ?
unit Unit1; interface uses SysUtils; type TStringArray = array of string; function SomeFunction(SomeParam: integer): TStringArray; ... implementation function SomeFunction(SomeParam: integer): TStringArray; begin SetLength(result, 3); result[0] := 'Alpha'; result[1] := 'Beta'; result[2] := 'Gamma'; end; ...
unit Unit1; interface uses SysUtils; type TStringArray = array of string; function SomeFunction(SomeParam: integer): TStringArray; ... implementation function SomeFunction(SomeParam: integer): TStringArray; begin SetLength(result, 3); result[0] := 'Alpha'; result[1] := 'Beta'; result[2] := 'Gamma'; end; ... end.
The golden rule is that the interface
section of a unit describes the data types used by the unit, and the types, classes and functions (their signatures) that reside in the unit. This is what all other units see. The implementation
section contains the implementation of the classes and functions. This is not visible to other units. Other units need to care about the interface of the unit, the 'contract' signed by this unit and the external unit, not the 'implementation details' found in the implementation section.
If you Delphi is fairly recent, you don't need to declare a new type, by declaring it as TArray<String>
.
Example copied and pasted from the answer above:
unit Unit1; interface function SomeFunction(SomeParam: integer): TArray<String>; implementation function SomeFunction(SomeParam: integer): TArray<String>; begin SetLength(result, 3); result[0] := 'Alpha'; result[1] := 'Beta'; result[2] := 'Gamma'; end; end.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With