2008. március 4., kedd

Convert your boolean values to the meaningful words


Problem/Question/Abstract:

How I convert boolean values to the words depending on the situation? For example, TRUE here means "Enabled", and FALSE there means "Failed"?

Answer:

Solve 1:

Here is the code snippet to do the job. If the second parameter is omitted, the function returns "TRUE" or "FALSE".
Modify the function declaration to change the default returning values. Expand TBooleanWordType and BooleanWord definitions to include more specific values if needed.

interface
{...}
type
  TBooleanWordType =
    (bwTrue, bwYes, bwOn, bwEnabled, bwSuccessful, bwOK, bwOne);
  {...}
function BoolToStr(AValue: boolean;
  ABooleanWordType: TBooleanWordType = bwTrue): string;
{...}
  {=====================================================}
implementation
{...}
const
  BooleanWord: array[boolean, TBooleanWordType] of string =
  (
    ('FALSE', 'No', 'Off', 'Disabled', 'Failed', 'Cancel', '0'),
    ('TRUE', 'Yes', 'On', 'Enabled', 'Successful', 'OK', '1')
    );

  {...}
    {-----------------------------------------------------}

function BoolToStr(AValue: boolean;
  ABooleanWordType: TBooleanWordType = bwTrue): string;
begin
  Result := BooleanWord[AValue, ABooleanWordType];
end; {--BoolToStr--}
{...}


Solve 2:

interface

function BoolToStr(b: boolean; TrueValue: string = '1'; FalseValue: string = '0'):
  string; overload;

implementation

function BoolToStr(b: boolean; TrueValue: string = '1'; FalseValue: string = '0'):
  string; overload;
begin
  if b then
    Result := TrueValue
  else
    Result := FalseValue,
end;

// example for italian language
s := BoolToStr(CheckBox1.Checked, 'Si', 'No');

Add this overloaded Function to the unit.


Solve 3:

const
  arrBooleanValues: array[Boolean] of ShortString = ('False', 'True');
var
  b: Boolean;
  s: string;
begin
  b := False;
  s := arrBooleanValues[b]; // 'False'
  b := True;
  s := arrBooleanValues[b]; // 'True'
end;

Nincsenek megjegyzések:

Megjegyzés küldése