Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
601 views
in Technique[技术] by (71.8m points)

xcode - Swift: how to use PREPROCESSOR Flags (like `#if DEBUG`) to implement API keys?

In Objective-C it was sometimes useful to use static string constants to define alternate API keys (for example to differentiate between RELEASE and DEBUG keys for analytics packages, like MixPanel, Flurry or Crashlytics):

#if DEBUG
static NSString *const API_KEY = @"KEY_A";
#else
static NSString *const API_KEY = @"KEY_B";
#endif

and then...

[Analytics startSession:API_KEY];

How does this translate to Swift, since the Swift compiler no longer uses a preprocessor?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Apple included full support for Swift preprocessor flags as of Xcode 8, so it's no longer necessary to set these values in "Other Swift Flags".

The new setting is called "Active Compilation Conditions", which provides top-level support for the Swift equivalent of preprocessor flags. You use it in exactly the same way as you would "Other Swift Flags", except there's no need to prepend the value with a "-D" (so it's just a little cleaner).

From the Xcode 8 release notes:

Active Compilation Conditions is a new build setting for passing conditional compilation flags to the Swift compiler. Each element of the value of this setting passes to swiftc prefixed with -D, in the same way that elements of Preprocessor Macros pass to clang with the same prefix. (22457329)

enter image description here

You use the above setting like so:

#if DEBUG
    let accessToken = "DebugAccessToken"
#else
    let accessToken = "ProductionAccessToken"
#endif

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...