Our DNA is written in Swift

Minimum/Maximum of Multiple Values

MadIvad asks:

Is there some sort of math function for the minimum of a set of values? I have searched the docs and not found one reference to math in iPhone OS2.2, and min only returns the like of ‘minimum’ for different control values. or for stating what the minimum of the integer or NSUInt class etc…

Does a function/class/anything exist that would simply return the lowest value of 2 or more values?

Boy, that was easy. There are compiler macros defined that work on any scalar datatype. MIN(a,b) and MAX(a,b). Note the case.

And you can stack those:

double a=1.0;
double b=3.0;
double c=2.0;
double m = MIN(MIN(a,b),c);

Compiler macros are causing the Pre-Compiler to replace the macros in your code for much more complicated syntax. This step happens before the compilation step. So the compiler only sees the more complicated code with all #defines replaced and all #imports inserted.

This is one possible definition of MIN:

#define MIN(i, j) ((i)<(j)?(i):(j))

You can see that there are no data types in this definition. And there don’t need to be any because the ?: operator works just as well for ints and floats. Compiler macros with parameters may look like functions, but really they are nothing but intelligent code replacements.

Categories: Q&A

Leave a Comment

%d bloggers like this: