1

I've got a project written in Swift 3 that has a number of #if ... #elses scattered throughout; they just check for a certain variable (defined with the -D compiler flag) which is set by my xcode project to know if the project is being built in xcode or with the package manager and does some imports accordingly. For example,

#if XCODE_BUILD
// do some imports that work when built with xcode
#else
// do some imports that won't work when built with xcode
#endif

The code builds just fine via either method.

But, when I select the option to upgrade to Swift 4 (either of the options offered -- "Minimize inference" or "Match Swift 3 behavior"), the code fails to compile so the migration fails. It appears that the #ifs are not being respected or the XCODE_BUILD variable isn't being defined, since the failures occur in the imports that shouldn't happen when being built from Xcode.

Does Swift 4 do something different with #ifs? Does Xcode somehow not define the compiler flags while doing the migration?

Philip
  • 1,526
  • 1
  • 14
  • 25

2 Answers2

2

You can use #if, #else and #endif, resulting in:

#if XCODE_BUILD
// do some imports that work when built with xcode
#else
// do some imports that won't work when built with xcode
#endif

Apple docs here.

Another answer with some additional details can be found here: https://stackoverflow.com/a/24152730/118091

runmad
  • 14,846
  • 9
  • 99
  • 140
  • Yeah sorry, that was a typo in my question, i wrote `ifdef` but meant `if`. What you've got here is what I've been doing. The problem remains that the `#if #else #endif` directives don't seem to work when upgrading to swift 4 – Philip Nov 03 '17 at 18:59
1

Previously, I was using the 'Other Swift Flags' build setting in Xcode to pass '-DXCODE_BUILD'. Apparently that setting doesn't work for Swift 4. The new setting that does work is 'Active Compilation Conditions' (it should be set to include XCODE_BUILD, no need for the -D flag).

Philip
  • 1,526
  • 1
  • 14
  • 25
  • This question has more info on this buried in one of the more recent answers: https://stackoverflow.com/questions/24003291/ifdef-replacement-in-the-swift-language/24152730#24152730 – Philip Nov 05 '17 at 05:05