2

How do I access a preprocessor macro in Xcode from Swift code for a string I've defined? Other stackoverflow posts show how to create the macros, but do not show me how to access them in code sufficiently.

For example, I have defined a constant called HELLO_WORLD_STRING = "Hello World!" in Preprocessor Macros Not Used in Precompiled Headers in the build settings as in the image:

Preprocessor Macros Not Used in Precompiled Headers

How would I print that constant in the debug window, just as an example?

I actually need to use the value of the app name to set the title of a navigation bar, but I would like to take this route in order to do that.

I have tried using #if ... #endif statements, but the constant was not recognized.

daniel
  • 1,446
  • 3
  • 29
  • 65
  • What language are you using? Swift eschews the use of macros. #ifdef work, but defines, not so much. – Hack Saw Dec 06 '18 at 08:03
  • I'm using Swift. – daniel Dec 06 '18 at 08:04
  • And I have to ask: what benefit do you think you'd get by retrieving this value from the build system, rather than setting it for your self in your application delegate, say? – Hack Saw Dec 06 '18 at 08:05
  • As far as I can tell, it's not possible in Swift. You can get the full path of the executable with Bundle.main.executablePath. – Hack Saw Dec 06 '18 at 08:06
  • Just for convenience. Just in case I change the app name in settings and forget to set it in code. – daniel Dec 06 '18 at 08:06
  • I used to take the value from Bundle.main like you describe, but then I would have to use string manipulations. I'm just looking for a simpler and better way to do what I have already been doing, just for the sake of doing something more perfect than before. – daniel Dec 06 '18 at 08:08
  • Plus the knowledge I gain will come in useful in the future for when I use preprocessor macros. – daniel Dec 06 '18 at 08:09
  • It's nice to learn something new to keep life interesting. – daniel Dec 06 '18 at 08:13
  • 1
    Yeah, so Swift is valiantly trying to kill off the use of macros, as they can make code hard to reason about, being one more place one needs to look for constants. – Hack Saw Dec 06 '18 at 08:15

1 Answers1

4

If you want to use syntax like:

 #if DEBUG_API_CALL
    print("Start loading \(method) \(url)")
 #endif

You have to add DEBUG_API_CALL (or other your name) to Active Compilation Conditions in the build settings tab:

Active Compilation Conditions in the build settings tab

Maciej Gad
  • 1,701
  • 16
  • 21