在 OC 中,我们经常会使用 DEBUG
标记来区分开发版本和发行版本,例如,控制调试信息的打印.
但是在使用 Swift 之后,我们发现DEBUG
不能正常工作.原因是 Swift 中没有DEBUG
这个标记.例如下面的代码:
func GUILog<T>(_ message: T, fileName: String = #function, methodName: String = #function, lineNumber: Int = #line) {
#if DEBUG
print("\(methodName)[\(lineNumber)]:\(message)")
#endif
}
虽然并不会报错,但是始终不会有打印.
解决方案
在 Build Settings
中搜索 other swift flags

点击图中红色框内部(注意不是直接点击+
),会出现一个这样的对话框.(可能已经有其他标记,如果你使用了 cocoapods
的话,不过不用在意),点击左下角的+ ,或者双击任意空白行,输入-DDEBUG
.

点击其它任意区域.结果如图

现在,DEBUG
就能正常工作了!
可以通过调整模式来进行测试:

把图中的地方改成Release
,即可进行测试.
Tips
这个编译标记可以随便定义,并不是只能是DEBUG
,只要标记能够对应,即可正常工作.编译器只是会看,在Debug
模式下,有哪些标记.(或者在 Release
模式下有哪些标记.)例如:

代码:
func GUILog<T>(_ message: T, fileName: String = #function, methodName: String = #function, lineNumber: Int = #line) {
#if DEFAULT
print("\(methodName)[\(lineNumber)]:\(message)")
#endif
}
网友评论