How To Create Custom Compilation Check

Sometimes you need to check the current platform like iOS or tvOS, another time you want to add some logs in only debug build.

If you don’t know how to do it you can read my previous post about default compilation checks.

In this post, you’ll learn how to create a new compilation check.

When can you use a custom compilation check?

For example, when you want to execute some code only in extensions. In extensions, you have shared code and it can be useful to add some code only for example in NotificationService or App Clips.

Let’s create a new one.

1 Open project
2 Select Target
3 Select Build Settings
4 Search for customs flags
5 Add flag you need

Let’s say you created the MyCustomCondition condition.

When this part of the code is executed?

When you add a new one for example in the main app target and Debug build, it’ll be only in the main app and during the debug build. For example, every time you create a new project or add a new extension to the project by default there is DEBUG and it gives you the option to add #if DEBUG in all places.

So you have your new one, in this case, it’s MyCustomCondition and you can just put it into code.

struct ContentView: View {
    
var body: some View {
        #if MyCustomCondition
        
Text(“It shows only in main app in Debug build”)
        
#endif
        
Text(“Hello, world!”)
            .
padding()
    }
}

If you add a new extension like App Clips and you won’t add MyCustomCondition to it then view in App Clips won’t show that Text(“It…”)

How To Test It

Run your app in Debug build.

The result you’ll see is:

When you build Release version you won’t see the first line.

If you don’t know how to change build version check it here.

Release version: