DEV Community

Evan Deaubl
Evan Deaubl

Posted on • Originally published at appsdissected.com

Keep your debug toolkit handy but hidden using conditional compilation

When you’ve been working on an app for a while, especially as it gets large, you often start to include snippets of code in the app that have been useful for debugging your app in the past. Such debugging code may be as simple as log statements, to as complex as adding full screens to your interface, activated by controls that you add to your interface for debugging only.

Such tools become an integral part of your debugging environment; you don’t want to throw them out. But do you really want to ship those in your app? It makes your app bigger and slower. You could comment them out before you release, but after a marathon debug session, do you trust that you’ll comment out again all of the debugging tools you enabled?

How can I keep my debugging addons, but ensure they aren’t in the version I deploy to the App Store?

There is a way: you can use a feature of Swift called conditional compilation to enable debugging code on your debug build. If you still have Objective-C code, you’re still in luck: a similar feature called preprocessor macros can provide the same functionality.


We’ll start with the happy path. If you’ve created your project with a recent version of Xcode (at least 9.3, so within the past year or so), you’re already set, and you can skip down to the part where we talk about the code itself (or you can go through it to verify your settings are there).

If you have an older project, you’ll need to add a couple of build settings for the following code to work:

Open your project, switch to the Build Settings tab, show All build settings, and select Levels.

Find Active Compilation Conditions, and add DEBUG under the project setting, as above.

If you have Objective-C code as well, find Preprocessor Macros and add DEBUG=1 to the project setting.

Once you have those set, you’re ready to hide your debug code.

Even though the two features have different names, compilation conditions and preprocessor macros, the code to wrap your debug code with is exactly the same, and it’s really easy:

#if DEBUG
   // My debug code is here
#endif

When you do your builds for the simulator and your development devices, all of your debug code will be enabled, ready for you to use. When you build an archive for App Store release or TestFlight, DEBUG will not be defined, and all of that code will disappear, ensuring your app stays fast and lean.

You can keep all your debugging addons AND keep them to yourself.


Did you like this tip? The next tip on your Xcode lag not being (entirely) Xcode's fault is already waiting for you.

Or sign up to get every tip straight to your inbox, plus newsletter-only tips and deeper dives on website articles and discounts on future product launches.

This post originally published at Apps Dissected.

Top comments (0)