Automatic Casting Using XML

I am loving the E4X stuff in ActionScript 3. Once you get your mind wrapped around it and if you don’t have to deal with namespaces it is very nice. Namespaces can be useful too, I just wish you could turn a namespace-agnostic-mode on and off. I just discovered a cool trick I thought I’d share with you. I found it when I was iterating through the properties of two objects to test if they were equal. The properties of one object were all Strings because it was parsed from a comma-delimited file. So, some Booleans or Numbers were strings of "true" or "10.5" while their counter-parts I was testing against were the real true and 10.5. You’d think to accomplish this you’d need a bunch of if statements that cast the values to the same type and test them. That could get messy. And what about casting Booleans. Has to be manual since there is no parseBoolean method. And NULL, same thing. So, I tried using E4X XML to test it. Doing this:

trace("true" == true, XML("true") == true); 

Gives you this: false true This is because E4X will do automatic casting

celebrex oral 500 mgflagyl and cipro togethernexiumlipitor dosagenexium over the counter 500 mg

for you. Wonderful! Now I had my solution. Just cast all values to XML first before comparing it (or assigning it). Works with Numbers (of all types), Booleans, and Strings.

One Response to “Automatic Casting Using XML”

  1. Tyler Wright Says:

    The casting isn’t quite pure. XML(“true”) is still of type XML, and so trace(XML("true") === true); outputs false. The comparison XML("56") == 56 returns true, but the expression XML("56") + 1 evaluates to 561.

    I’m still hoping to find one more step that can bring this solution home, I’d really like an easy method for simple-type casting like this.