Using Compiler Variables in Swift

In Objective-C, I had a bunch of compiler flags set in Build Settings β†’ Other C Flags, which were used in the code. For instance:

Flag => -DPortNumber = 1

And in the code, I was able to access it through @(PortNumber)

This does not work in Swift, and I cannot find the answer.

+5
source share
1 answer

The -D flag for C compilers defines a preprocessor macro. There are no preprocessor macros in Swift. Therefore, if you want to do something like:

 // compile with -DPORT_NUMBER 31337 var port = PORT_NUMBER // error 

... You can not. Swift is designed to make the source code syntactically complete before compilation. If you can disconnect blocks from it during assembly, you can break the tool chain's ability to make sure your code is correct. (This is partly due to the fact that preprocessor macros in C are textual substitutions: you can use them to overwrite any part of the language, and not just to fill in the values ​​for variables.)

The Swift compiler has the -D flag, but its use is more limited: you can use it only for building configurations . So, if you want to do something like the following, you will be cool:

 // compile with -DUSE_STAGING_SERVER #if USE_STAGING_SERVER var port = 31337 #else var port = 80 #endif 

Note that unlike C, everything inside the #if block must be syntactically completed. (For example, you cannot only put the func declaration line in the #if block and leave the body of the function unconditional.)

Of course, this will not help you if you want the configuration value set at compile time to be set in your code. For this, I would recommend alternative approaches. Xcode can still perform textual substitution in resource files, such as property lists. (Note that the Info.plist that comes with your application is full of things like $(TARGET_NAME) , for example.) So, you can include the package resource with your application, the contents of which are filled at compile time according to your project settings, then read your port number.

+12
source

Source: https://habr.com/ru/post/1210494/


All Articles