I want to write a function that swaps two variables in Objective-C, and it should be applicable to all types (primitive and class objects). So far what I've found are the xor swap but this only works on integers but not floats or class objects, and I looked for a generic way to write such function but as I understood from several responses Objective-C doesn't support generic programming, so I can't do it like templates in C++ or generic classes in Java. Is there a way to achieve swapping any two variables of same type (primitive and class objects) in Objective-C?
Asked
Active
Viewed 1,053 times
0
-
1While not technically a duplicate, because ObjC is a perfect superset of C the answer (no) is identical to http://stackoverflow.com/questions/2637856/is-there-an-equivalent-of-stdswap-in-c. I recommend KennyTM's answer in particular. – Rob Napier Jan 05 '14 at 16:36
-
@RobNapier KennyTM's solution worked. – hakuna matata Jan 05 '14 at 16:52
-
Also look at http://stackoverflow.com/questions/3982348/implement-generic-swap-macro-in-c, which does provide a memcpy-based solution (but it wouldn't safely work with objects). – Rob Napier Jan 05 '14 at 16:52
1 Answers
2
You cannot swap objects, because your code does not "have" objects. There is no variable containing an object. It has a pointer to an object.
You can swap this pointers as you would do this in pure C. This is, because pointers are pure C.

Amin Negm-Awad
- 16,582
- 3
- 35
- 50