Swift:如何使用 PREPROCESSOR 标志(如 `#if DEBUG` )来实现 API key ?

标签 swift xcode macros preprocessor xcode-build-settings

Objective-C 中,有时使用静态字符串常量来定义备用 API key 很有用(例如,区分分析包(如 MixPanel、Flurry 或 Crashlytics)的 RELEASE 和 DEBUG key ):

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

然后……

[Analytics startSession:API_KEY];

既然 Swift 编译器不再使用预处理器,这如何转化为 Swift?

最佳答案

Xcode 8 起,Apple 全面支持 Swift 预处理器标志,因此不再需要在“其他 Swift 标志”中设置这些值。

新设置称为“事件编译条件”,它为预处理器标志的 Swift 等价物提供顶级支持。您使用它的方式与您使用“其他 Swift 标志”的方式完全相同,除了不需要在值前加上“-D”(所以它只是更简洁一点)。

来自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

你像这样使用上面的设置:

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

关于Swift:如何使用 PREPROCESSOR 标志(如 `#if DEBUG` )来实现 API key ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38813906/

相关文章:

ios - 更改 UIScrollView 内容大小

ios - UIButton 不执行不同类中函数的操作

ios - UITableView分页: inserting new cells while scrolling weird behavior

ios - 如何获取 ViewController 的引用

swift - 如何只填充自定义 UIView 矩形的一部分?

c++ - PCH 警告 : header stop cannot be in a macro or #if block

ios - 文件 “XXX” 不存在

iphone - 模态视图中的淡出过渡

macros - 如何在 lisp 中编写 'destructive' dolist 宏

git - PS1 环境变量在 Mac 上不起作用