What is a Swift macro?
You probably heard the term “macro” before in the context of programming. That’s perhaps because programming languages such as C/C++ have macros as well.
A macro is a structure that lets us define a code pattern that is being replaced by the compiler with a specific set of instructions.
Let’s see a short C example:
#define SQUARE(x) ((x) * (x)) int num = 5; int result = SQUARE(num);
In our preceding code, we declare a macro called SQUARE
that receives one parameter named X
, and our compiler replaces it with (
x) *(x)
.
The initial question that comes to mind is this: why? Can’t we just define a function?
So, in this case, a simple function that calculates a number’s square can be helpful here.
But a macro’s primary goal is not to replace functions, as they are great for several reasons:
- Code reuse: Notice that code reuse is not “functionality reuse.” Code reuse is where we...