886

In C/C++/Objective C you can define a macro using compiler preprocessors. Moreover, you can include/exclude some parts of code using compiler preprocessors.

#ifdef DEBUG
    // Debug-only code
#endif

Is there a similar solution in Swift?

4
  • 1
    As an idea, you could put this in your obj-c bridging headers..
    – Matej
    Commented Jan 10, 2015 at 13:50
  • 80
    You really should award an answer as you have several to choose from, and this question has gotten you a lot of up votes.
    – David H
    Commented Aug 4, 2016 at 14:00
  • 1
    @Userthatisnotauser you totally missed the point. You ask a question, you get great answers - choose one. Don’t just ignore the time and effort.
    – David H
    Commented Jun 11, 2020 at 0:56
  • 3
    @Userthatisnotauser the poster has 19k points - people voted his answers but he doesn’t seem to care about people who help him. I always always choose an answer .
    – David H
    Commented Jun 11, 2020 at 1:04

19 Answers 19

1217

Yes you can do it.

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.

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

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

You can read my original post here.


IMPORTANT NOTE: -DDEBUG=1 doesn't work. Only -D DEBUG works. Seems compiler is ignoring a flag with a specific value.

27
  • 49
    This is the correct answer, although it should be noted that you can only check for the presence of the flag but not a specific value. Commented Jun 18, 2014 at 8:52
  • 24
    Additional note: On top of adding -D DEBUG as stated above, you also need to define DEBUG=1 in Apple LLVM 6.0 - Preprocessing -> Preprocessor Macros.
    – MLQ
    Commented Mar 26, 2015 at 15:25
  • 43
    I couldn't get this to work until I changed the formatting to -DDEBUG from this answer: stackoverflow.com/a/24112024/747369.
    – Kramer
    Commented Jul 23, 2015 at 16:30
  • 13
    @MattQuiros There's no need to add DEBUG=1 to Preprocessor Macros, if you don't want to use it in Objective-C code.
    – derpoliuk
    Commented Nov 16, 2015 at 11:24
  • 9
    @Daniel You can use standard boolean operators (ex: ` #if !DEBUG ` ) Commented Apr 22, 2016 at 13:48
416

As stated in Apple Docs

The Swift compiler does not include a preprocessor. Instead, it takes advantage of compile-time attributes, build configurations, and language features to accomplish the same functionality. For this reason, preprocessor directives are not imported in Swift.

I've managed to achieve what I wanted by using custom Build Configurations:

  1. Go to your project / select your target / Build Settings / search for Custom Flags
  2. For your chosen target set your custom flag using -D prefix (without white spaces), for both Debug and Release
  3. Do above steps for every target you have

Here's how you check for target:

#if BANANA
    print("We have a banana")
#elseif MELONA
    print("Melona")
#else
    print("Kiwi")
#endif

enter image description here

Tested using Swift 2.2

8
  • 4
    1.with white space work also, 2.should set the flag only for Debug?
    – c0ming
    Commented Apr 25, 2016 at 2:45
  • 3
    @c0ming it depends on your needs, but if you want something to happen only in debug mode, and not in release, you need to remove -DDEBUG from Release.
    – cdf1982
    Commented Jul 17, 2016 at 19:51
  • 1
    After i set the custom flag -DLOCAL, on my #if LOCAl #else #endif, it falls into the #else section. I duplicated the original target AppTarget and rename it to AppTargetLocal & set its custom flag.
    – Perwyl Liu
    Commented Jul 20, 2016 at 6:48
  • 3
    @Andrej do you happen to know how to make XCTest recognise the custom flags as well? I realise it falls into #if LOCAL , the intended result when i run with the simulator and falls into #else during testing. I want it to falls into #if LOCAL as well during testing.
    – Perwyl Liu
    Commented Jul 20, 2016 at 7:05
  • 3
    This should be the accepted answer. The current accepted answer is incorrect for Swift as it only applies to Objective-C. Commented Sep 3, 2016 at 11:01
190

A major change of ifdef replacement came up with Xcode 8. i.e use of Active Compilation Conditions.

Refer to Building and Linking in Xcode 8 Release note.

New build settings

New setting: SWIFT_ACTIVE_COMPILATION_CONDITIONS

“Active Compilation Conditions” is a new build setting for passing conditional compilation flags to the Swift compiler.

Previously, we had to declare your conditional compilation flags under OTHER_SWIFT_FLAGS, remembering to prepend “-D” to the setting. For example, to conditionally compile with a MYFLAG value:

#if MYFLAG1
    // stuff 1
#elseif MYFLAG2
    // stuff 2
#else
    // stuff 3
#endif

The value to add to the setting -DMYFLAG

Now we only need to pass the value MYFLAG to the new setting. Time to move all those conditional compilation values!

Please refer to below link for more Swift Build Settings feature in Xcode 8: http://www.miqu.me/blog/2016/07/31/xcode-8-new-build-settings-and-analyzer-improvements/

7
  • Is there anyway to disable a set Active Compilation Conditions at build time ? I need to disable the DEBUG condition when building the debug configuration for testing.
    – Jonny
    Commented Sep 1, 2017 at 2:56
  • 2
    @Jonny The only way I've found is to create a 3rd build config for the project. From the Project > Info tab > Configurations, hit '+', then duplicate Debug. You can then customize the Active Compilation Conditions for this config. Don't forget to edit your Target > Test schemes to use the new build configuration!
    – matthias
    Commented Oct 10, 2017 at 21:04
  • 2
    This should be the correct answer..its the only thing that worked for me on xCode 9 using Swift 4.x !
    – shokaveli
    Commented Apr 11, 2018 at 21:19
  • 2
    BTW, In Xcode 9.3 Swift 4.1 DEBUG is already there in Active Compilation Conditions and you don't have to add anything to check for DEBUG configuration. Just #if DEBUG and #endif. Commented Jun 3, 2018 at 13:10
  • I think this is both off-topic, and a bad thing to do. you do not want to disable Active Compilation Conditions. you need a new and different configuration for testing - that will NOT have the "Debug" tag on it. Learn about schemes. Commented Jun 18, 2018 at 7:20
185

In many situations, you don't really need conditional compilation; you just need conditional behavior that you can switch on and off. For that, you can use an environment variable. This has the huge advantage that you don't actually have to recompile.

You can set the environment variable, and easily switch it on or off, in the scheme editor:

enter image description here

You can retrieve the environment variable with NSProcessInfo:

    let dic = NSProcessInfo.processInfo().environment
    if dic["TRIPLE"] != nil {
        // ... do secret stuff here ...
    }

Here's a real-life example. My app runs only on the device, because it uses the music library, which doesn't exist on the Simulator. How, then, to take screen shots on the Simulator for devices I don't own? Without those screen shots, I can't submit to the AppStore.

I need fake data and a different way of processing it. I have two environment variables: one which, when switched on, tells the app to generate the fake data from the real data while running on my device; the other which, when switched on, uses the fake data (not the missing music library) while running on the Simulator. Switching each of those special modes on / off is easy thanks to environment variable checkboxes in the Scheme editor. And the bonus is that I can't accidentally use them in my App Store build, because archiving has no environment variables.

16
  • 68
    Watch out: Environment Variables are set for all build configurations, they can't be set for individual ones. So this is not a viable solution if you need the behaviour to change depending on whether it's a release or a debug build.
    – Eric
    Commented Jun 10, 2015 at 15:50
  • 8
    @Eric Agreed, but they are not set for all scheme actions. So you could do one thing on build-and-run and a different thing on archive, which is often the real-life distinction you want to draw. Or you could have multiple schemes, which also a real-life common pattern. Plus, as I said in my answer, switching environment variables on and off in a scheme is easy.
    – matt
    Commented Jun 10, 2015 at 15:54
  • 11
    Environment variables do NOT work in archive mode. They are only applied when the app is launched from XCode. If you try to access these on a device, the app will crash. Found out the hard way.
    – iupchris10
    Commented Sep 14, 2015 at 21:10
  • 3
    @iupchris10 "Archiving has no environment variables" are the last words of my answer, above. That, as I say in my answer, is good. It's the point.
    – matt
    Commented Sep 14, 2015 at 21:24
  • 1
    This is exactly the correct solution for the XCTest case, where you want a default behavior when the application is running in the simulator, but you want to strictly control the behavior in the tests.
    – Stan
    Commented Jun 2, 2017 at 17:57
100

As of Swift 4.1, if all you need is just check whether the code is built with debug or release configuration, you may use the built-in functions:

  • _isDebugAssertConfiguration() (true when optimization is set to -Onone)
  • _isReleaseAssertConfiguration() (true when optimization is set to -O) (not available on Swift 3+)
  • _isFastAssertConfiguration() (true when optimization is set to -Ounchecked)

e.g.

func obtain() -> AbstractThing {
    if _isDebugAssertConfiguration() {
        return DecoratedThingWithDebugInformation(Thing())
    } else {
        return Thing()
    }
}

Compared with preprocessor macros,

  • ✓ You don't need to define a custom -D DEBUG flag to use it
  • ~ It is actually defined in terms of optimization settings, not Xcode build configuration
  • ✗ Undocumented, which means the function can be removed in any update (but it should be AppStore-safe since the optimizer will turn these into constants)

  • ✗ Using in if/else will always generate a "Will never be executed" warning.

9
  • 1
    Are these built-in functions evaluated at compile time or runtime?
    – ma11hew28
    Commented Feb 28, 2016 at 19:59
  • @MattDiPasquale Optimization time. if _isDebugAssertConfiguration() will be evaluated to if false in release mode and if true is debug mode.
    – kennytm
    Commented Mar 1, 2016 at 4:52
  • 2
    I can't use these functions to opt out some debug-only variable in release, though. Commented Apr 12, 2016 at 1:04
  • 4
    Are these functions documented somewhere? Commented May 2, 2016 at 17:27
  • 7
    As of Swift 3.0 & XCode 8, these functions are invalid.
    – CodeBender
    Commented Nov 3, 2016 at 21:38
93

Xcode 8 and above

Use Active Compilation Conditions setting in Build settings / Swift compiler - Custom flags.

  • This is the new build setting for passing conditional compilation flags to the Swift compiler.
  • Simple add flags like this: ALPHA, BETA etc.

Then check it with compilation conditions like this:

#if ALPHA
    //
#elseif BETA
    //
#else
    //
#endif

Tip: You can also use #if !ALPHA etc.

1
81

There is no Swift preprocessor. (For one thing, arbitrary code substitution breaks type- and memory-safety.)

Swift does include build-time configuration options, though, so you can conditionally include code for certain platforms or build styles or in response to flags you define with -D compiler args. Unlike with C, though, a conditionally compiled section of your code must be syntactically complete. There's a section about this in Using Swift With Cocoa and Objective-C.

For example:

#if os(iOS)
    let color = UIColor.redColor()
#else
    let color = NSColor.redColor()
#endif
8
  • 38
    "For one thing, arbitrary code substitution breaks type- and memory-safety." Doesn't a pre-processor do its work before the compiler does (hence the name)? So all these checks could still take place.
    – Thilo
    Commented Jun 4, 2014 at 1:42
  • 10
    @Thilo I think what it breaks is IDE support Commented Jun 4, 2014 at 20:37
  • 1
    I think what @rickster is getting at is that C Preprocessor macros have no understanding of type and their presence would break Swift's type requirements. The reason macros work in C is because C allows implicit type conversion, which means you could put your INT_CONST anywhere a float would be accepted. Swift would not allow this. Also, if you could do var floatVal = INT_CONST inevitably it would breakdown somewhere later when the compiler expects an Int but you use it as a Float (type of floatVal would be inferred as Int). 10 casts later and its just cleaner to remove macros...
    – Ephemera
    Commented Jun 7, 2014 at 1:45
  • I'm trying to use this but it doesn't seem to work, it's still compiling the Mac code on iOS builds. Is there another setup screen somewhere that has to be tweaked? Commented Feb 21, 2015 at 21:59
  • 1
    @Thilo you are correct - a pre-processor does not break any type or memory safety.
    – tcurdt
    Commented Jun 10, 2016 at 9:47
60

isDebug Constant Based on Active Compilation Conditions

Another, perhaps simpler, solution that still results in a boolean that you can pass into functions without peppering #if conditionals throughout your codebase is to define DEBUG as one of your project build target's Active Compilation Conditions and include the following (I define it as a global constant):

#if DEBUG
    let isDebug = true
#else
    let isDebug = false
#endif

isDebug Constant Based on Compiler Optimization Settings

This concept builds on kennytm's answer

The main advantage when comparing against kennytm's, is that this does not rely on private or undocumented methods.

In Swift 4:

let isDebug: Bool = {
    var isDebug = false
    // function with a side effect and Bool return value that we can pass into assert()
    func set(debug: Bool) -> Bool {
        isDebug = debug
        return isDebug
    }
    // assert:
    // "Condition is only evaluated in playgrounds and -Onone builds."
    // so isDebug is never changed to true in Release builds
    assert(set(debug: true))
    return isDebug
}()

Compared with preprocessor macros and kennytm's answer,

  • ✓ You don't need to define a custom -D DEBUG flag to use it
  • ~ It is actually defined in terms of optimization settings, not Xcode build configuration
  • Documented, which means the function will follow normal API release/deprecation patterns.

  • ✓ Using in if/else will not generate a "Will never be executed" warning.

0
52

My two cents for Xcode 8:

a) A custom flag using the -D prefix works fine, but...

b) Simpler use:

In Xcode 8 there is a new section: "Active Compilation Conditions", already with two rows, for debug and release.

Simply add your define WITHOUT -D.

4
  • Thanks for mentioning that there are TWO ROWS FOR DEBUG AND RELEASE
    – Yitzchak
    Commented Nov 13, 2016 at 6:28
  • anyone tested this in release? Commented Nov 21, 2016 at 15:41
  • This is the updated answer for swift users. ie without -D.
    – Mani
    Commented Dec 19, 2017 at 9:29
  • I had tried to set the flag in "Other Swift Flags" but nothing happened. Thanks for your suggestion to set it in "Active Compilation Conditions". It works. Commented Sep 12, 2020 at 4:04
50

Moignans answer here works fine. Here is another piece of info in case it helps,

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

You can negate the macros like below,

#if !RELEASE
    let a = 2
#else
    let a = 3
#endif
29

In Swift projects created with Xcode Version 9.4.1, Swift 4.1

#if DEBUG
#endif

works by default because in the Preprocessor Macros DEBUG=1 has already been set by Xcode.

So you can use #if DEBUG "out of box".

By the way, how to use the condition compilation blocks in general is written in Apple's book The Swift Programming Language 4.1 (the section Compiler Control Statements) and how to write the compile flags and what is counterpart of the C macros in Swift is written in another Apple's book Using Swift with Cocoa and Objective C (in the section Preprocessor Directives)

Hope in future Apple will write the more detailed contents and the indexes for their books.

26

There are some processors that take an argument and I listed them below. you can change the argument as you like:

#if os(macOS) /* Checks the target operating system */

#if canImport(UIKit) /* Check if a module presents */

#if swift(<5) /* Check the Swift version */

#if targetEnvironment(simulator) /* Check envrionments like Simulator or Catalyst */

#if compiler(<7) /* Check compiler version */

Also, You can use any custom flags like DEBUG or any other flags you defined

#if DEBUG
print("Debug mode")
#endif
25

XCODE 9 AND ABOVE

#if DEVELOP
    //print("Develop")
#elseif PRODUCTION
    //print("Production")
#else
    //
#endif
0
9

After setting DEBUG=1 in your GCC_PREPROCESSOR_DEFINITIONS Build Settings I prefer using a function to make this calls:

func executeInProduction(_ block: () -> Void)
{
    #if !DEBUG
        block()
    #endif
}

And then just enclose in this function any block that I want omitted in Debug builds:

executeInProduction {
    Fabric.with([Crashlytics.self]) // Compiler checks this line even in Debug
}

The advantage when compared to:

#if !DEBUG
    Fabric.with([Crashlytics.self]) // This is not checked, may not compile in non-Debug builds
#endif

Is that the compiler checks the syntax of my code, so I am sure that its syntax is correct and builds.

5

![In Xcode 8 & above go to build setting -> search for custom flags ]1

In code

 #if Live
    print("Live")
    #else
    print("debug")
    #endif
1
  • 1
    You have hit on it here! Swift #if looks at custom flags NOT preprocessor macros. Please update your answer with the content from the link, often times links will break after a while
    – Dale
    Commented May 18, 2019 at 7:15
4
func inDebugBuilds(_ code: () -> Void) {
    assert({ code(); return true }())
}

Source

2
  • 1
    This isn't conditional compilation. While useful , its just a plain old runtime conditional. The OP is asking after compiletime for metaprogramming purposes
    – Shayne
    Commented Jan 18, 2019 at 2:00
  • 3
    Just add @inlinable in front of func and this would be the most elegant and idiomatic way for Swift. In release builds your code() block will be optimized and eliminated altogether. A similar function is used in Apple's own NIO framework.
    – mojuba
    Commented May 12, 2019 at 8:42
2

This builds on Jon Willis's answer that relies upon assert, which only gets executed in Debug compilations:

func Log(_ str: String) { 
    assert(DebugLog(str)) 
}
func DebugLog(_ str: String) -> Bool { 
    print(str) 
    return true
}

My use case is for logging print statements. Here is a benchmark for Release version on iPhone X:

let iterations = 100_000_000
let time1 = CFAbsoluteTimeGetCurrent()
for i in 0 ..< iterations {
    Log ("⧉ unarchiveArray:\(fileName) memoryTime:\(memoryTime) count:\(array.count)")
}
var time2 = CFAbsoluteTimeGetCurrent()
print ("Log: \(time2-time1)" )

prints:

Log: 0.0

Looks like Swift 4 completely eliminates the function call.

1
  • Eliminates, as in removes the call in its entirety when not in debug - due to the function being empty? That would be perfect.
    – Johan
    Commented Apr 24, 2018 at 6:40
0

Swift 5 update for matt's answer

let dic = ProcessInfo.processInfo.environment
if dic["TRIPLE"] != nil {
// ... do your secret stuff here ...
}
0

You can create an enum like this named AppConfiguration to make your raw values type safe.

enum AppConfiguration: String {
    
    case debug
    case release
    
}

put that in a static variable

struct Constants {
    
    static let appConfiguration: AppConfiguration {
        
        #if DEBUG
        return .debug
        #else
        return .release
        #endif
        
    }
    
}

which you can then use around your entire project like this -

switch Constants.appConfiguration {

case .debug:    

print("debug")

case .release:

print("release")

}
3
  • 1
    It doesn't make any sense to have this as a var, please dont use this. Also, indent your code, it looks awful.
    – J. Doe
    Commented Jul 17 at 8:51
  • Why not? It makes the code a-lot more readable and you don't have to use a preprocessor statement everywhere this condition is required. Commented Jul 19 at 5:13
  • a var is a computed property. You return a static value. It makes much more sense to just convert it to a let
    – J. Doe
    Commented Jul 19 at 6:15

Not the answer you're looking for? Browse other questions tagged or ask your own question.