简体   繁体   English

如何在Swift中编写编译时代码?

[英]How do I write compile time code in Swift?

I'm wanting to write some compile-time code (ie code that is run when the project is compiled). 我想编写一些编译时代码(即,在编译项目时运行的代码)。 This is used in other languages (eg Java) to write code generators (eg Dagger 2). 这在其他语言(例如Java)中用于编写代码生成器(例如Dagger 2)。

Is this possible in Swift? 在Swift中有可能吗? If so how? 如果可以,怎么办? It is rather important for what I'm attempting to do. 对于我要尝试的操作,这非常重要。

Your question is very vague. 您的问题非常模糊。 There are multiple reasons for writing compile-time code, and it all depends on what you want to do. 编写编译时代码有多种原因,而这完全取决于您要执行的操作。

If you want to write conditional code that only runs based on certain compile-time directives, use 如果要编写仅基于某些编译时指令运行的条件代码,请使用

#if build configuration
    statements
#else
    statements
#endif

If you want to generate code like a preprocessor would do in macros to reduce code duplication, then you should simply change your mindset and use swift functions and generics that will achieve the same result, only better. 如果要像预处理器那样在宏中生成代码以减少代码重复,那么您只需更改思维方式,并使用迅速的函数和泛型即可达到相同的结果,只是效果更好。 (Simple macros like #define xxx ... are replaced by let xxx = ... ). (简单的宏如#define xxx ...替换为let xxx = ... )。

Finally, if you want to generate huge amounts of code then Swift isn't the language for you, you should use a dedicated code generator or some scripting language. 最后,如果您想生成大量代码,那么Swift不是您想要的语言,则应使用专用的代码生成器或某些脚本语言。 For example, if you're looking to generate code for a state machine, use dedicated tools for that task that take as input UML. 例如,如果您要为状态机生成代码,请为该任务使用专用工具作为输入UML。 Obviously you'll have a hard time today finding tools that output Swift code (least of which being that Swift itself is a moving target), but that'll change over time. 显然,今天您很难找到可以输出Swift代码的工具(最重要的是Swift本身就是一个移动的目标),但是随着时间的推移,它会发生变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM