Swift 语言中的 #ifdef 替换 [英] #ifdef replacement in the Swift language
问题描述
在 C/C++/Objective C 中,您可以使用编译器预处理器定义宏.此外,您可以使用编译器预处理器包含/排除部分代码.
In C/C++/Objective C you can define a macro using compiler preprocessors. Moreover, you can include/exclude some parts of code using compiler preprocessors.
#ifdef DEBUG
// Debug-only code
#endif
Swift 中是否有类似的解决方案?
Is there a similar solution in Swift?
推荐答案
是的,你可以做到.
在 Swift 中,您仍然可以使用#if/#else/#endif"预处理器宏(尽管受到更多限制),如 Apple 文档.举个例子:
In Swift you can still use the "#if/#else/#endif" preprocessor macros (although more constrained), as per Apple docs. Here's an example:
#if DEBUG
let a = 2
#else
let a = 3
#endif
现在,您必须在别处设置DEBUG"符号.在Swift Compiler - Custom Flags"部分的Other Swift Flags"行中设置它.您可以使用 -D DEBUG
条目添加 DEBUG 符号.
Now, you must set the "DEBUG" symbol elsewhere, though. Set it in the "Swift Compiler - Custom Flags" section, "Other Swift Flags" line. You add the DEBUG symbol with the -D DEBUG
entry.
像往常一样,您可以在调试或发布时设置不同的值.
As usual, you can set a different value when in Debug or when in Release.
我用真实的代码测试过它,它工作正常;不过在操场上似乎没有人认出它.
I tested it in real code and it works; it doesn't seem to be recognized in a playground though.
您可以阅读我的原始帖子 此处.
You can read my original post here.
重要说明: -DDEBUG=1
不起作用.只有 -D DEBUG
有效.似乎编译器忽略了具有特定值的标志.
IMPORTANT NOTE: -DDEBUG=1
doesn't work. Only -D DEBUG
works. Seems compiler is ignoring a flag with a specific value.
这篇关于Swift 语言中的 #ifdef 替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!