Craig Grummitt – Before I forget

Discoveries in Swift and iOS development.

‘as’ isn’t the equivalent of typing.

·

I guess I hadn’t thought too deeply about it, but I always thought that the ‘as’ Operator was the equivalent of typing a variable.

pseudo code example:
[sourcecode language=”actionscript3″]
type(test) = test as type
[/sourcecode]
or to give a real world example:

[sourcecode language=”actionscript3″]
var myVar:String=’3′;
var myInt:int=int(myVar);
[/sourcecode]
or alternatively:
[sourcecode language=”actionscript3″]
var myInt2:int=myVar as int;
trace(myInt,myInt2);
[/sourcecode]
But this code will trace:
3 0

I’ve realised that while typing a variable actually converts the variable to the requested datatype, ‘as’ merely informs the compiler to expect a certain variable to be of a certain datatype.

In the above example, ‘myString as int’ doesn’t work because myString isn’t an int.

However, if initially we had defined myVar like so:
[sourcecode language=”actionscript3″]
var myVar:*=3;
[/sourcecode]

The code would have no problem as myVar is an int.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *