在 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”(所以它只是更简洁一点)。
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 ofPreprocessor Macros
pass to clang with the same prefix. (22457329)
你像这样使用上面的设置:
#if DEBUG
let accessToken = "DebugAccessToken"
#else
let accessToken = "ProductionAccessToken"
#endif
关于Swift:如何使用 PREPROCESSOR 标志(如 `#if DEBUG` )来实现 API key ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38813906/