Swift macros #if - #endif
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.
- Goto: Project → Info → Configurations
- Click + to add your macros
- Goto: Target → Build Settings →
Other Swift Flags
- You need to add flags to the macros (
Dev
→-Ddev
,Staging
→-Dstg
) - Always should add with prefix
-D
without space to use inside code
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.
- Goto → Edit Scheme...
- Run → Info → Build Configuration
- Select scheme in Build Configuration to run in particular scheme
Let's grow together 🌱
Cheers 🍻