Is it possible to implement swapping routine in ActionScript 3.0 similar to C++ std::swap? I mean something like
public static function Swap(var a, var b):void
{
var c = a;
a = b;
b = c;
}
and then
var a:int = 3;
var b:int = 5;
Swap(a,b);
trace(a, " ", b); // there must be 5 3
It doesn't work "as is" for integers because they're passed by value, not ref into the Swap routine.
Unfortunately you can't implement a swap in this way, because ActionScript 3, Java, and many other languages pass primitives and object references by value. That link will give you the details, but basically this means that the references inside the function aren't the same as the references outside the function (even though they indeed refer to the same object). Therefore, fiddling with the parameter references in the function has no effect outside the function. You're forced to do the swap inline.
If you really needed some swap behavior in a function, you'd have to wrap the parameters in another object, and then you can change the inner reference:
public static function Swap(var a, var b)
{
var c = a.value;
a.value = b.value;
b.value = c;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With