在C/C++/Objective C中,可以使用编译器预处理器定义宏。此外,您可以使用编译器预处理器包含/排除代码的某些部分。

#ifdef DEBUG
    // Debug-only code
#endif

Swift中有类似的解决方案吗?


当前回答

func inDebugBuilds(_ code: () -> Void) {
    assert({ code(); return true }())
}

来源

其他回答

在GCC_PREPROCESSOR_DEFINITIONS构建设置中设置DEBUG=1后,我更喜欢使用函数进行以下调用:

func executeInProduction(_ block: () -> Void)
{
    #if !DEBUG
        block()
    #endif
}

然后,只需在此函数中包含我希望在调试构建中省略的任何块:

executeInProduction {
    Fabric.with([Crashlytics.self]) // Compiler checks this line even in Debug
}

与以下各项相比的优势:

#if !DEBUG
    Fabric.with([Crashlytics.self]) // This is not checked, may not compile in non-Debug builds
#endif

是编译器检查我的代码的语法,所以我确信它的语法是正确的,并进行编译。

Xcode 8对ifdef替换进行了重大更改。即使用主动编译条件。

请参阅Xcode 8发行说明中的构建和链接。

新建生成设置

新设置:SWIFT_ACTIVE_COMPILATION_CONDITIONS

“Active Compilation Conditions” is a new build setting for passing conditional compilation flags to the Swift compiler.

以前,我们必须在OTHER_SWIFT_flags下声明条件编译标志,记住在设置前加上“-D”。例如,要有条件地使用MYFLAG值进行编译:

#if MYFLAG1
    // stuff 1
#elseif MYFLAG2
    // stuff 2
#else
    // stuff 3
#endif

要添加到设置的值-DMYFLAG

现在我们只需要将值MYFLAG传递到新设置。是时候移动所有这些条件编译值了!

有关Xcode 8中更多Swift Build Settings功能,请参阅以下链接:http://www.miqu.me/blog/2016/07/31/xcode-8-new-build-settings-and-analyzer-improvements/

![在Xcode 8及以上版本中,转到构建设置->搜索自定义标志]1

在代码中

 #if Live
    print("Live")
    #else
    print("debug")
    #endif

我的两分钱用于Xcode 8:

a) 使用-D前缀的自定义标志工作正常,但。。。

b) 更简单的使用:

在Xcode 8中有一个新的部分:“活动编译条件”,已经有两行,用于调试和发布。

只需添加无D的定义。

马特回答的Swift 5更新

let dic = ProcessInfo.processInfo.environment
if dic["TRIPLE"] != nil {
// ... do your secret stuff here ...
}