Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift compiler macro / flag for String value alternative

Tags:

swift

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.

like image 440
respectTheCode Avatar asked Feb 28 '26 20:02

respectTheCode


1 Answers

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.

like image 177
Sulthan Avatar answered Mar 03 '26 17:03

Sulthan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!