Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

swift - Swift语言中的#ifdef替换(#ifdef replacement in the Swift language)

In C/C++/Objective-C you can define a macro using compiler preprocessors.

(在C / C ++ / Objective-C中,您可以使用编译器预处理程序定义宏。)

Moreover, you can include/exclude some parts of code using compiler preprocessors.

(此外,您可以使用编译器预处理程序包含/排除部分代码。)

#ifdef DEBUG
    // Debug-only code
#endif

Is there a similar solution in Swift?

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

  ask by mxg translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes you can do it.

(是的,你可以做到。)

In Swift you can still use the "#if/#else/#endif" preprocessor macros (although more constrained), as per Apple docs .

(在Swift中,按照Apple docs的规定 ,您仍然可以使用“#if /#else /#endif”预处理器宏(尽管有更多限制)。)

Here's an example:

(这是一个例子:)

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

Now, you must set the "DEBUG" symbol elsewhere, though.

(现在,您必须在其他位置设置“ DEBUG”符号。)

Set it in the "Swift Compiler - Custom Flags" section, "Other Swift Flags" line.

(在“ Swift编译器-自定义标志”部分的“其他Swift标志”行中进行设置。)

You add the DEBUG symbol with the -D DEBUG entry.

(您将DEBUG符号与-D DEBUG条目一起添加。)

As usual, you can set a different value when in Debug or when in Release.

(与往常一样,您可以在Debug或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 .

(您可以在这里阅读我的原始帖子。)


IMPORTANT NOTE: -DDEBUG=1 doesn't work.

(重要说明: -DDEBUG=1不起作用。)

Only -D DEBUG works.

(仅-D DEBUG有效。)

Seems compiler is ignoring a flag with a specific value.

(似乎编译器正在忽略具有特定值的标志。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...