respectTheCode
respectTheCode

Reputation: 43086

Swift compiler macro / flag for String value alternative

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.

Upvotes: 3

Views: 1781

Answers (2)

Sulthan
Sulthan

Reputation: 130102

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.

Upvotes: 1

MoDJ
MoDJ

Reputation: 4425

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"

Upvotes: 0

Related Questions