I added TEST=1
in the Preprocessor Macros
section of the project target's Build Settings
, and whenever I use it in code, the preprocessor thinks it's not defined.
For example, having:
#if TEST
// a
#else
// b
#endif
has this behavior:
// b
// b
This is because the preprocessor can't find TEST
(even if it's defined as 1
, as I previously stated) so it treats it as being false
.
Is there any way to solve these problems?
Edit:
My use case is related to multiple Project Targets. So, say that the initial target is named First
, which has the TEST
preprocessor macro defined with value 1
.
If I create another project target named Second
with no preprocessor macros defined and want to add some code for it only if TEST
is 0
(false
/not defined), I'll put it in the #else
block (// b
).
Knowing that syntax coloring and autocomplete works for // b
, it looks like it works ok, but if I change the current target to the First
one (pun intended) and even build it, it still works as Second
is selected.
Preprocessor Macros are directives executed by the compiler, so they're not part of Objective C. We've used them many times before with the #import statement. But to stay with our Lite and Pro example: you can use a Preprocessor if/then statement to check which version is being compiled.
After Xcode 8, Apple has added another setting called Active Compilation Conditions where you can add your pre processor macro without the "-D" option and swift will be able to recognize it. Show activity on this post. You need to set swift custom flags to access the pre-macro processors in swift.
The Swift compiler does not include a preprocessor. Instead, it takes advantage of compile-time attributes, builds configurations, and language features to accomplish the same functionality.
Swift. Preprocessor macros are used to bring context to a build, allowing you to transform how your app is compiled depending on why it's being built.
If you want to do it like this in Swift, you should add a User-Defined
setting named OTHER_SWIFT_FLAGS
in your Build Settings
like this:
And then in your code you type:
#if TEST1
// Debug
#endif
#if TEST2
// Release
#endif
I don't know why you need this, but it may be interesting to look into native Xcode Target, to use specific behavior for multiple apps with same root project. If this is what you want, you should look into an article this: AppCoda using Targets with Xcode.
Just go to target->Edit Scheme -> Run -> Info and check the Build Configuration. Now while adding the Preprocessor Macros in build setting just make sure you are adding the macro for correct build configuration and correct target.
I tried by adding for both debug and release build as above for my target App (Test-ObjectiveC). So when i tried below code with this setting, u can see the syntax color accordingly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With