Andrei Herford
Andrei Herford

Reputation: 18745

How to correctly use #ifdef DEBUG / RELEASE values in Swift Code?

This question is NOT about how to create/use Objective-C like #ifdef statements in Swift, which has been discussed in other questions.

This question is about how to use existing Objective-C code from existing #ifdef statements in Swift:

I am working on migrating my existing iOS 9+ app from Objective-C to Swift. While large parts of the app still use Objective-C new View Controllers, Classe, etc. are added using Swift.

The Objective-C code uses #ifdef statements to create different code for debugging and release and for different app targets like a Freemium and a Pro version:

#ifdef PRO_VER
    #define APP_NAME @"My App Pro"
#else
    #define APP_NAME @"My App"
#endif 

The Problem

When using these constants in Objective-C everything is fine. When using the same constants within the same target in Swift, they always have the non-pro value:

// Using in Objective-C within the Pro Target
NSLog(@"The objc app name is: %@", APP_NAME);

// Using in Swift within the Pro Target
print("The Swift app name is: \(APP_NAME)")


Output:
    The objc app name is: My App Pro
    The Swift app name is: My App

So, the same constant has different values when being used in Swift or Objective-C.

Of course, this could be solved by creating a static Objective-C method/property which returns the correct value which is then be used by the Swift code. However, this would be quite hacky and cumbersome.

Is there a better solution to get the correct values from within Swift code?

Upvotes: 1

Views: 4009

Answers (1)

matt
matt

Reputation: 535547

The Objective-C code uses #ifdef statements to create different code for debugging and release and for different app targets like a Freemium and a Pro version

You can't say #define in Swift. Instead:

  • Swift can use #if DEBUG to create different code for debugging and release.

  • To distinguish between custom defined constants, add them to the target's Active Compilation Conditions build setting.

Those are in fact the same thing, because the reason #if DEBUG works is that it is in the target's Active Compilation Conditions.

(And there are various other things that #if can distinguish between, such as Swift version, and whether we're compiling for the simulator or a device.)

Upvotes: 2

Related Questions