3

I'm having trouble replicating in Swift the Preprocessor Macro functionality offered by ObjC. I have heard that Swift has no preprocessor, so I'm looking for another way to implement this.

My end goal is to build my project using the command line tools, passing in a custom variable and value, which will be preprocessed and inserted into the code at specific points, before the build takes place.

This is the solution for ObjC:

Use this command to run a test:

xcodebuild \
    test \
    -scheme TestUserDefinedVariablesObjC \
    -destination 'platform=iOS Simulator,name=iPhone 6' \
    MY_VAR=42

I use MY_VAR in code like this:

int a = MY_VAR;

(I add MY_VAR to Preprocessor Macros in my target's Build Settings like this: MY_VAR=$(MY_VAR))

As a last resort, I could add pre-action to the scheme's Run phase that substitutes the correct values using sed or something like that, but it's not a great solution.

5
  • possible duplicate of Swift: iOS Deployment Target Command Line Flag Commented Dec 30, 2014 at 17:21
  • @David I'm looking to pass a variable from the command line to the app, not a constant. Commented Dec 30, 2014 at 17:57
  • Same difference. In Xcode set it up as MY_VAR=$(MY_VAR) Commented Dec 30, 2014 at 19:43
  • I read the linked question, but it doesn't show you would access it in Swift. Commented Dec 30, 2014 at 20:03
  • 1
    I'm looking for some way to retrieve the value. I tried MY_VAR=$(MY_VAR) in Other Swift Flags, but then using int a = MY_VAR; produces a Use of unresolved identifier 'MY_VAR' error. Commented Dec 30, 2014 at 20:08

2 Answers 2

0

Are you using different keyset/keyboard? If so check "

example: Preprocessor Macros in my target's Build Settings MY_VAR=\"42\"

check " character. Change it with this "

Sign up to request clarification or add additional context in comments.

Comments

0

Instead of using SED in a build-phase script, you could use the clang preprocessor. For example, put this in a file named macro-test.c

#if DEBUG
#define LOG(A) print(A)
#else
#define LOG(A) 
#endif

import Foundation

func hello()
{
    LOG("Hello, Swift macro!")
    
    let theAnswer = MY_CONST
    
    print("The answer = ", theAnswer)
}

Add a script build phase that runs the clang preprocessor:

#!/bin/sh
if [ $CONFIGURATION == "Debug" ] ;
then
    DEBUG="1"
else
    DEBUG="0"
fi
MY_CONST=42

clang -E -P -DMY_CONST=$MY_CONST -DOS=$OS -DDEBUG=$DEBUG "${SOURCE_ROOT}/macro-test.c" > "${SOURCE_ROOT}/macro-test.swift"

Add the generated swift file to the Xcode project.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.