Skip to content
DeveloperMemos

How to Execute Code Only in Debug Mode in Swift

Swift, Debugging, Xcode1 min read

When working with Swift, there are often situations where you need certain code to run exclusively during debugging. Whether it's for setting up developer-specific configurations or enabling additional logging, there are several methods to accomplish this task. In this article, we'll delve into three common approaches:

1. Using Preprocessor Macros

Preprocessor macros enable you to conditionally compile code based on the build configuration. Specifically, you can execute code only when building in Debug mode. Here's how you can implement it:

1#if DEBUG
2// Code to run only in Debug mode
3self.somethingA = 10
4self.somethingB = false
5self.somethingC = true
6#endif

In the above example, the specified code will be included only during Debug builds. When you build your app for release, this code won’t be part of the final product.

2. Xcode Flags

Xcode flags provide an alternative method for conditional execution. Follow these steps:

  • Open your Xcode project.
  • Navigate to Build Settings.
  • Search for “Swift Compiler – Custom Flags” and locate the “Other Swift Flags” section.
  • Add -DDEBUG to the Debug section and -DRELEASE to the Release section.

By doing this, you define custom flags that automatically set based on the build configuration.

3. Debugging in Xcode

Effective debugging is crucial for identifying issues in your Swift code. Here’s how to debug effectively:

  • Launch Xcode and open your project.
  • Set breakpoints in your code where you want to pause execution.
  • Run your app.
  • When your app hits a breakpoint, Xcode will pause execution and display a debug area with various details you can inspect.

Remember to use these techniques judiciously to avoid accidentally leaking developer-only settings into production builds. Happy Xcoding! 😊