Debug with the DEBUG preprocessor macro in Xcode
Testing shouldn’t mean using your production backend
Logging is a great way to know what is going on in your code, and solving those little problems (that may keep rearing their heads as you develop as a programmer).
But what if you could use
Macros to use different sections of code according to different situations. One such tool for this is the DEBUG
Difficulty: Beginner | Easy | Normal | Challenging
- Understanding of branching in Swift is assumed(guide HERE)
Build: A version of an App
Debug: A process to identify and remove errors
Macro: a programmable pattern which translates a certain sequence of input into a preset sequence of output
Preprocessor Macro: a preprocessor is a macro processor that is used automatically by the compiler to transform the app before compilation
Release: The final distribution version of an App
Moving on from logging
Logging to the console gives you access to a great debugging tool. I’ve already written a guide to logging in Swift (HERE).
But there are some situations where you would want to use a
#if/#else/#endif pattern switching on whether a debug build is being used or not.
The default Macro
By default, Xcode has a DEBUG
Preprocessor Macro that is set to 1 for
debug builds, and 0 for non-
debug builds (i.e.
Using the DEBUG macro
#if/#else/#endif is quite easy to use to detect if we have a
A common use of this is where you have a token for an API (say your backend, or a Firebase ID token or similar) and you want to use a different token when in
release mode — that is when you are developing and building the app on your machine or whether it is in use on a real user’s device.
let token = "ABC1234"
let token = "ZYX9876"
The practical application
The way I usually do this is by having a constants.swift file to separate out the token from my main code. You might want to avoid placing this into version control (Guide to gitignore HERE)
This can then be used anywhere in your code. For brevity, I’m accessing this from a viewcontroller and simply printing the token to the console.
when the code is run
is printed to the console. Great!
But what if you want to test your production API. No problem.
Switch the Build
By selecting configurations it is possible to switch to the
release configuration by going to Edit Scheme… and selecting
release. Need a hand? There’s an animated GIF right below:
The github link
This (rather basic) code is contained in the following link. When you run it, just expect a blank screen and a program that prints a string to the console.
Extend your knowledge
- Apple have details about the DEBUG preprocessor macro HERE
The Twitter contact:
Any questions? You can get in touch with me here