Sunday, April 3, 2011

From String to Boolean - casting problem

This is not a great discover, but sometimes it can help to save some time while wondering why there is true when should be false. I usually meet this situation while reading data from url GET parameters or from XML.

Let's check the example:



var stringTrue:String = 'true';
var stringFalse:String = 'false';


var boolDataTrue = new Boolean(stringTrue);
trace('#1 String true is casted to:', boolDataTrue);
//#1 String true is casted to: true


var boolDataFalse = new Boolean(stringFalse);
trace('#1 String false is casted to:', boolDataFalse);
//#1 String false is casted to: true



For this example I made two variables. In Boolean constructor ther's object as argument. But no matter what kind of string you put there it always deals it as 'true' expression

For quick and short fix you have to put there expresion that checks text and returns true or false as a proper type:


var boolDataTrue = new Boolean(stringTrue == 'true'?true:false);
trace('#2 String true is casted to:', boolDataTrue);
//#2 String true is casted to: true


var boolDataTrue = new Boolean(stringFalse == 'true'?true:false);
trace('#2 String true is casted to:', boolDataTrue);
//#2 String true is casted to: false


No comments:

Post a Comment