0

I've searched around but nothing useful for me founded.

What is the best way to write a swap method to exchange two primitive values in ObjectiveC?

You know the primitive types have different sizes, so if we pass them through something like void *, then how can we know about their size? (maybe one extra parameter for their size?)

in C#, it could be something like this :

void Swap<T>(ref T a, ref T b)
{
    T tmp = a;
    a = b;
    b = tmp;
}

An idea could be creating a temp memory block with the same size of input types, then copying them as memory blocks with a method like memcpy or something.

But I prefer something more natural in ObjectiveC, if there is a better one.

Majid
  • 3,128
  • 1
  • 26
  • 31

1 Answers1

0

If the type is truly a primitive, you can use the XOR swap algorithm.

x = x ^ y;
y = x ^ y;
x = x ^ y;

In a macro, this could look as follows:

#define SWAP(a, b) (a^=b;b^=a;a^=b;)

But care should always be taken with macros.

Otherwise, you can try this: https://stackoverflow.com/a/3982430/2471910

Community
  • 1
  • 1
Trenin
  • 2,041
  • 1
  • 14
  • 20
  • Right - it won't work on pointers due to the compiler. It will work on other data types of the same size (long for example). – Trenin Jun 11 '13 at 16:54