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

#ifdef DEBUG
    // Debug-only code
#endif

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


当前回答

这是基于Jon Willis的答案,该答案依赖于断言,该断言仅在调试编译中执行:

func Log(_ str: String) { 
    assert(DebugLog(str)) 
}
func DebugLog(_ str: String) -> Bool { 
    print(str) 
    return true
}

我的用例是记录打印语句。以下是iPhone X上发布版本的基准:

let iterations = 100_000_000
let time1 = CFAbsoluteTimeGetCurrent()
for i in 0 ..< iterations {
    Log ("⧉ unarchiveArray:\(fileName) memoryTime:\(memoryTime) count:\(array.count)")
}
var time2 = CFAbsoluteTimeGetCurrent()
print ("Log: \(time2-time1)" )

打印:

Log: 0.0

看起来Swift 4完全消除了函数调用。

其他回答

从Swift 4.1开始,如果你只需要检查代码是用调试还是发布配置构建的,你可以使用内置函数:

_isDebugAssertConfiguration()(当优化设置为-Onone时为true)_isReleaseAssertConfiguration()(当优化设置为-O时为true)(在Swift 3+上不可用)_isFastAssertConfiguration()(当优化设置为-Ounchecked时为true)

e.g.

func obtain() -> AbstractThing {
    if _isDebugAssertConfiguration() {
        return DecoratedThingWithDebugInformation(Thing())
    } else {
        return Thing()
    }
}

与预处理器宏相比,

✓ 您不需要定义自定义的-D DEBUG标志来使用它~它实际上是根据优化设置定义的,而不是Xcode构建配置✗ 未记录,这意味着该函数可以在任何更新中删除(但它应该是AppStore安全的,因为优化器会将这些转换为常量)这些内容一度被删除,但由于缺少@testable属性而重新公开,未来的Swift命运未卜。✗ 在if/else中使用将始终生成“将永远不会执行”警告。

没有Swift预处理器。(一方面,任意代码替换破坏了类型和内存安全。)

不过,Swift确实包含了构建时配置选项,因此您可以有条件地包含某些平台或构建样式的代码,或者响应您使用-D编译器参数定义的标志。但是,与C不同,代码的有条件编译部分必须在语法上完整。在将Swift与Cocoa和Objective-C结合使用中有一节介绍了这一点。

例如:

#if os(iOS)
    let color = UIColor.redColor()
#else
    let color = NSColor.redColor()
#endif

这是基于Jon Willis的答案,该答案依赖于断言,该断言仅在调试编译中执行:

func Log(_ str: String) { 
    assert(DebugLog(str)) 
}
func DebugLog(_ str: String) -> Bool { 
    print(str) 
    return true
}

我的用例是记录打印语句。以下是iPhone X上发布版本的基准:

let iterations = 100_000_000
let time1 = CFAbsoluteTimeGetCurrent()
for i in 0 ..< iterations {
    Log ("⧉ unarchiveArray:\(fileName) memoryTime:\(memoryTime) count:\(array.count)")
}
var time2 = CFAbsoluteTimeGetCurrent()
print ("Log: \(time2-time1)" )

打印:

Log: 0.0

看起来Swift 4完全消除了函数调用。

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

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