Showing posts with label type. Show all posts
Showing posts with label type. Show all posts

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


Thursday, February 3, 2011

Numerical attributes in XML & no value in code

I know it's a stupid case, but sometimes I forgot about simple things.

Problem:
we have numerical value in XML like:

<component itemHeight="20" itemsVSpace="10" .../>

in code we want to use those values

itemLabel.y = index*( _contentXML.@itemHeight + _contentXML.@itemsVSpace);

Result? We receive zero. Because attribute value is used as String and + works as concatenation. Then multiple converts value to zero. We have to cast values at the begining to expected type:

itemLabel.y = index*( int(_contentXML.@itemHeight) + int(_contentXML.@itemsVSpace) );