Is there a way to do #define, #ifdef and the other powerful macros in Swift?
2 Answers
Swift doesn't have a preprocessor and can't use C macros. There are some alternatives though. For constants you can just use a let statement. For example:
let defaultHeight = 100
There is also some support for build configurations. They have this format.
#if build configuration && !build configuration
statements
#elseif build configuration
statements
#else
statements
#endif
You can replace "build configuration" with the functions os()
and arch()
that return true or false. os()
can take OSX or iOS as arguments while arch()
can take x86_64, arm, arm64 and i386 as arguments.
You can see more about how Swift replaces C macros here

- 63,902
- 28
- 145
- 142
Simple Macros Where you typically used the #define directive to define a primitive constant in C and Objective-C, in Swift you use a global constant instead. For example, the constant definition #define FADE_ANIMATION_DURATION 0.35 can be better expressed in Swift with let FADE_ANIMATION_DURATION = 0.35. Because simple constant-like macros map directly to Swift global variables, the compiler automatically imports simple macros defined in C and Objective-C source files
reference: Page 40, Simple Macros