Determinate the build configuration at runtime in Swift using macro

Antoine Barrault
2 min readJan 24, 2017

--

Today when developing iOS apps is common to have to work with multiple environments inside the same project (staging and production for example). I am going to show you how to change environment based on build configuration, like this you will never release an app in production pointing out development endpoints.

Let’s say that you have 3 build configurations (Debug, Release and AdHoc):

Build configurations for our project

Now we need to add flags to the AdHoc and Debug versions, look for Other Swift Flags in the Build Settings tab and add :

  • “-DADHOC” for Adhoc build configuration
  • “-DDEBUG” for Debug build configuration
Other Swift flags with values setted

There are no need to call the flag DEBUG or ADHOC but you need to add -D at the start of the word you going to use.

I made a small struct to check the flag at runtime using macro.

Then to check if you are in production :

let production = Env.isProduction() 

That’s it!

You may asked how can I test my app in production. No there are no need to run the app on release.

We going to add a new Environment Variable to our Scheme, let’s call it forceProduction:

Creating new environment variable

Now just update our struct:

Struct updated to consider environment variable

Now if you want to test in production just click on the check box.

--

--

Antoine Barrault

I write Swift code. Dad of two awesome children with a wonderful wife. Currently Mobile engineer @ Teads.