3

Is there a way to do #define, #ifdef and the other powerful macros in Swift?

ABeanSits
  • 1,725
  • 1
  • 17
  • 34
  • 1
    possible duplicate of [#ifdef replacement in swift language](http://stackoverflow.com/questions/24003291/ifdef-replacement-in-swift-language) – njzk2 Jun 05 '14 at 18:43

2 Answers2

5

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

Connor Pearson
  • 63,902
  • 28
  • 145
  • 142
0

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

https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/BuildingCocoaApps.pdf

dibi
  • 3,257
  • 4
  • 24
  • 31
Bogdan
  • 1,286
  • 9
  • 12