Search code examples
xcodepreprocessor

Add and Retrieve GCC_PREPROCESSOR_DEFINITIONS value in Swift


I've multiple target created in my project. Now I'm planing to add a string UUID to all the targets GCC_PREPROCESSOR_DEFINITIONS aka Preprocessor macro.

I'll add this to Alpha, Beta, Lite & Prod. And based on the UUID string I can know about which variant is running and use corresponding configurations to handle dynamically

Lets say for Target1 I want to add UUID="<UUID for Target1>" and I'll add 4 uuids in each target.

Now I've two challange -

  1. Add UUID's to all the preprocessor macros
  2. Retrieve the UUID at the very beginning of App life cycle so that I can configure the app based on the UUID

For the 1st option, I've searched over the internet but found solution for adding int values and while retrieving the value is being checked using if elif and else in both swift & objective-C

But I want to add a string value and while retrieving I want to assign that value to my local swift variable and use that uuid.

How can I retrieve string value from Preprocessor macro to Swift varibale?

May be a basic question, but I didn't find anything for this.


Solution

  • It is possible, but we need the help of OC since Swift's Marco is weak.


    1. First, since OC is a superset of C language, and C language supports string type Marcos, so we can define Marco like this

    S_UUID="2EBEA32B-60AE-48FA-90E1-686DD83512DE"

    I added an S_ prefix to prevent the symbol from conflicting with system symbols.

    1. Add these two preprocessor macros:
    //turns x into a string literal
    #define STRINGIZE(x) #x
    //uses STRINGIZE(x) to turn the value of x into a string.
    #define STRINGIZE_VALUE_OF(x) STRINGIZE(x)
    
    1. Then you can parse the S_UUID to OC's String type with
      NSString *uuid = @STRINGIZE_VALUE_OF(S_UUID);
    

    I have created the POC project here. It also has the code to use the retrieved UUID in Swift.