Ios – In absence of preprocessor macros, is there a way to define practical scheme specific flags at project level in Xcode project

iosswift

Before swift I would define a set of schemes for alpha, beta, and distribution builds. Each of these schemes would have a set of macros that were defined to gate certain behaviors at the project level. The simplest example is the DEBUG=1 macro that is defined by default for all Xcode projects in the default scheme for the Run build. One could query #ifdef DEBUG … and make decisions in the code accordingly, even compiling out non-necessary code.

It seems that this type of configurational gating is not as easy using swift, as macros are not supported. Can someone suggest a comparable approach, I don't care if the code is compiled out, per se. I would like to gate features based on build scheme, though.

Best Answer

In Swift you can still use the "#if/#else/#endif" preprocessor macros (although more constrained), as per Apple docs. Here's an example:

#if DEBUG
    let a = 2
#else
    let a = 3
#endif

Now, you must set the "DEBUG" symbol elsewhere, though. Set it in the "Swift Compiler - Custom Flags" section, "Other Swift Flags" line. You add the DEBUG symbol with the -D DEBUG entry.

(Build Settings -> Swift Compiler - Custom Flags) enter image description here

As usual, you can set a different value when in Debug or when in Release.

I tested it in real code; it doesn't seem to be recognized in a playground.

Related Topic