2

In Objective-C we could add a C Flag of -DVAR_NAME=@\"string value\" and then get the value with NSString *var = VAR_NAME.

How do we do this in Swift?

An example of this would be defining an api host based on the current git branch. Say the branch is feature1 and it should connected to https://feature1.example.com. A shell script can easily find the current branch and add the C Flag. Then in Objective-C we can use the branch from the shell script to generate the api host url.

Update

I am not asking about boolean flags. I need to pass a string value.

Update 2

So far all I can come up with is to use a build script to generate a swift class.

Update 3

Another option is to add custom keys to the Info.plist. This isn't always an acceptable solution but for configuration values this works.

respectTheCode
  • 40,233
  • 16
  • 70
  • 84

2 Answers2

1

Define a condition like this:

var window: UIWindow?

#if MYDEF
  var textureRenderThread : TextureRenderThread?
#endif

In the Project->Build Settings->Swift Compiler->Custom Flags

Set "-D MYDEF" as the value for "Other Swift Flags"

MoDJ
  • 4,060
  • 1
  • 25
  • 59
1

Macros are evil. They have been abused for things like this and it's not a clean solution. You have the following options (some of them already mentioned by you).

  1. Info.plist

The most simple, easy to read and edit. Not good for big configurations.

  1. Your own .plist.

Easy to read and edit (even from command line tools before the build, see PlistBuddy tool). Better for bigger configurations.

  1. Auto generated code

Your code can contain an expression that can be matched easily, e.g.

let myConfigValue = "${MY-CONFIG-VALUE}".

You can replace those values easily using command line tools, e.g. sed. This basically replicates macros without using C preprocessor. This is not very clean but usable if you already have a build system that you don't want to change.

  1. Multiple code variants

You can have a Swift file with configuration constants and use #if to switch between them.

Sulthan
  • 118,286
  • 20
  • 194
  • 245
  • I agree that macros have been abused. One of the great things about adopting Swift is that it is forcing everyone to revisit old code and processes. – respectTheCode Jun 15 '15 at 13:14
  • @respectTheCode As for my recommendations, I prefer a separate plist file. Changing `Info.plist` during build time would be reflected in versioning systems so I prefer a file that can be made to be ignored by versioning. As for reading the config, it can be abstracted into a very simple class. – Sulthan Jun 15 '15 at 13:19