How to Determine Which Configuration Is Running in Swift
In How to Manage Environment Settings in Xcode, we created build configurations and schemes for Development, QA, and Production environments, allowing us to switch settings depending on the environment.
Sometimes, you may want to determine which build configuration is currently being used at runtime and execute different code accordingly.
Here, we'll explain how to detect which configuration is active when running in Swift.
This assumes Build Configurations and Schemes have already been created. If not, please return to the index of How to Manage Environment Settings in Xcode and add them first.
How to Determine Which Configuration Is Running in Swift
You may have seen code like the following when checking whether your app is running in Debug mode in Swift:
#if DEBUG
[Code Block A]
#else
[Code Block B]
#endif
This is called a conditional compilation block. At compile time, the compiler evaluates the conditions you set with compilation condition options, and only the matching code is compiled and executed.
So in the example above, if the compilation condition is DEBUG, then [Code Block A] will be compiled and executed; otherwise, [Code Block B] will be.
You can use these compilation condition options to determine which build configuration is active at runtime.
Click your Target in Xcode, go to the Build Settings tab, and search for Active Compilation Conditions.
Since the Debug configurations were created by duplicating the default Debug configuration, you'll see that DEBUG is already inherited from the Project-level Build Settings.
This is where compilation conditions are defined, and the #if DEBUG directive comes from this setting.
If you only need to distinguish between Debug and non-Debug configurations, this setup is sufficient.
If you want to identify the environment (scheme) regardless of Debug or Release, you can add your own compilation conditions like this:
On the Swift side, for example, if you want to display the selected environment in the text of a UILabel named label, you can do the following:
#if DEV
label.text = "Development"
#elseif QA
label.text = "QA"
#else
label.text = "Production"
#endif
Of course, you can define different values for both Debug and Release configurations within each environment, and even set multiple compilation conditions.
For example, if you want to execute different code not only by environment but also by Debug vs. Release, you can set it up like this:
In that case, you could write code like this to handle each compilation condition separately:
#if DEV
...
#elseif QA
...
#else
...
#endif
#if DEBUG
...
#else
...
#endif
That's how to determine which configuration is running in Swift.