在C/C++/Objective C中,您可以使用编译器预处理器定义宏。 此外,您还可以使用编译器预处理器包含/排除一些代码部分。
#ifdef DEBUG
// Debug-only code
#endif
在 Swift 中是否有类似的解决方案?
在C/C++/Objective C中,您可以使用编译器预处理器定义宏。 此外,您还可以使用编译器预处理器包含/排除一些代码部分。
#ifdef DEBUG
// Debug-only code
#endif
在 Swift 中是否有类似的解决方案?
Xcode版本为9.4.1,使用Swift 4.1创建的Swift项目
#if DEBUG
#endif
由于在预处理器宏 DEBUG=1 已经被 Xcode 设置,所以默认情况下可正常工作。
因此,您可以“开箱即用”地使用 #if DEBUG。
顺便提一句,如何使用条件编译块通常在苹果的书籍《The Swift Programming Language 4.1》(部分:编译器控制语句)中有介绍,而如何编写编译标志以及Swift中C宏的对应项在另一本苹果的书籍《Using Swift with Cocoa and Objective C》(部分:预处理指令)中有介绍。
希望苹果在未来能编写更详细的内容和索引。
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
GCC_PREPROCESSOR_DEFINITIONS
的 DEBUG=1
后,我建议使用一个函数来进行调用:func executeInProduction(_ block: () -> Void)
{
#if !DEBUG
block()
#endif
}
然后只需在此函数中包含任何我想在Debug构建中省略的块:
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
编译器会检查我的代码语法,以确保它的语法正确并能够构建。
func inDebugBuilds(_ code: () -> Void) {
assert({ code(); return true }())
}
func
前面添加@inlinable
,这将成为Swift中最优雅和惯用的方式。在发布版本中,您的code()
块将被优化并完全消除。苹果自己的NIO框架中使用了类似的函数。 - mojuba这是基于 Jon Willis 的答案构建的,它依赖于 assert,只在 Debug 编译中执行:
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 5 版本更新,详见马特的回答
let dic = ProcessInfo.processInfo.environment
if dic["TRIPLE"] != nil {
// ... do your secret stuff here ...
}
enum AppConfiguration: String {
case debug
case release
}
struct Constants {
static var appConfiguration: AppConfiguration {
#if DEBUG
return .debug
#else
return .release
#endif
}
}
然后您可以像这样在整个项目中使用它 -
if Constants.appConfiguration == .debug {
print("debug")
} else {
print("release")
}