Skip to content

Swift macros #if - #endif

Platform Language License

During iOS development we come across multiple environments (Staging & Production).

We can use #if to differentiate Development, Staging & Production at one time, we can create different scheme to take the build easily.

Example:

//MARK:- Macros
var APIURL: String {
    #if dev
        return "http://192.168.0.1/"
    #elseif stg
        return "http://demo.example.com/"
    #else
        return "http://live.example.com/"
    #endif
}
print(APIURL)

You can use #if dev anywhere in the project to achieve code execution. Suppose, If you need to show their logs only in development and not in staging then you can write only inside dev and not in staging or live.

Example: You will be having logs only in development and the entire print will work under development scheme. Logs will not show/print for staging and live.

Follow the below steps to add macros into project.

  1. Goto: Project → Info → Configurations
  2. Click + to add your macros

iOSMacros

  1. Goto: Target → Build Settings → Other Swift Flags
  2. You need to add flags to the macros (Dev-Ddev, Staging-Dstg)
  3. Always should add with prefix -D without space to use inside code

iOSMacros1

Overview:

Now you need to create multiple scheme, so that you can change the scheme & run to get different line code execution for a same variable or function or class.

iOSMacros2

  1. Goto → Edit Scheme...
  2. Run → Info → Build Configuration
  3. Select scheme in Build Configuration to run in particular scheme

iOSMacros3

Let's grow together 🌱

Cheers 🍻