Preprocessor macros in Swift

Tomas Camin
2 min readNov 29, 2016

--

Hang on. There is no such thing, the Swift compiler has no preprocessor.

While that’s true, if you’re working on a Xcode project started in the ancient Objective-C era, there’s a good chance that you’ve been relying on Preprocessor Macros to manage build configuration specific flags that conditionally compile blocks of code. This works so nice that you probably more than once started naively typing #if MY_FLAG in you shiny new Swift code. Well that works (in the sense that it compiles) but it does not what you would expect because MY_FLAG is not defined in Swift!

🔥🔥🔥 (guess what happens?)

You probably read that Swift does include its own build-time configuration options, however keeping them manually aligned with the preprocessor macros is kind of tedious. I wrote a very simple Ruby script to copy preprocessor defines in Swift’s Other Swift Flags that we launch as a Run Script in the target’s Build Phases. It’s bare bone so it might not apply to all scenarios, but I guess it could be useful for others out there.

The script uses the awesome CocoaPods/Xcodeproj to edit Xcode’s .pbxproj and simply rewrites the OTHER_SWIFT_FLAGS. We added a sentinel define, THESEWILLBEOVERWRITTENBYRUNSCRIPT, to reminds us that the value will be overwritten everytime you run the project (actually when the .pbxproj changes).

For now it works.

How do I add the script to Xcode?

Click on to the Build Phases tab in your app’s target, then add a new Run Script by clicking on the + button.

In the Shell field type /usr/bin/ruby, and below paste the entire script.

--

--