在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完全消除了函数调用。

其他回答

莫伊尼昂的回答很好。这是另一条信息,以防有帮助,

#if DEBUG
    let a = 2
#else
    let a = 3
#endif

您可以像下面这样否定宏,

#if !RELEASE
    let a = 2
#else
    let a = 3
#endif

XCODE 9及以上

#if DEVELOP
    //print("Develop")
#elseif PRODUCTION
    //print("Production")
#else
    //
#endif

有一些处理器接受一个参数,我在下面列出了它们。您可以随意更改参数:

#if os(macOS) /* Checks the target operating system */

#if canImport(UIKit) /* Check if a module presents */

#if swift(<5) /* Check the Swift version */

#if targetEnvironment(simulator) /* Check envrionments like Simulator or Catalyst */

#if compiler(<7) /* Check compiler version */

此外,您可以使用任何自定义标志,如DEBUG或您定义的任何其他标志

#if DEBUG
print("Debug mode")
#endif
func inDebugBuilds(_ code: () -> Void) {
    assert({ code(); return true }())
}

来源

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

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

例如:

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