我们如何利用宏来推动 MVVM 架构的采用
Over the past few years, our team of iOS engineers has grown significantly (and continues to grow!), as has the size of the codebase.
过去几年,我们的 iOS 工程师团队规模显著扩大(并且仍在 增长!),代码库也随之膨胀。
To accommodate this scale my team, Client Architecture, has been working hard to standardize around a consistent MVVM architecture. And while this effort has been mostly well received, during the initial rollout we received feedback that the new guidelines led to an annoying increase in boilerplate. At first we tried to cut back on repetitive code as much as possible with helper methods and shared utilities, but we eventually hit a wall because sometimes it isn’t possible to pare everything away. For this boilerplate which cannot be easily abstracted we’ve increasingly turned to a Swift feature called “Macros”.
为了适应这种规模,我的团队——Client Architecture——一直在努力围绕一致的 MVVM 架构进行标准化。虽然这项工作总体上得到了积极响应,但在最初推广时,我们收到了反馈:新指南导致了令人厌烦的样板代码增加。起初,我们尝试通过辅助方法和共享工具尽可能减少重复代码,但最终遇到了瓶颈,因为有时无法将所有内容都精简掉。对于这些无法轻松抽象的样板代码,我们越来越多地转向 Swift 的一项名为“Macros”的功能。
What are Swift Macros?
什么是 Swift Macros?
At their most fundamental, Macros are tags that are attached to existing code to generate new code at compile time. The actual Macro implementation does this by operating on the abstract syntax tree (AST) of the source code they are attached to and generating a new tree which can either be inserted into the attached class/struct/method/etc, or alongside it. This process is fully integrated into the compiler, so generated code is treated exactly the same as manually written code, and thus benefits from all the same compiler optimizations and seamlessly fits into the build process. Given these performance optimizations and the ability to transform code based on structure and semantics rather than just the text, Macros are incredibly powerful when it comes to generating boilerplate.
从根本上说,宏是附加在现有代码上的标记,用于在编译时生成新代码。宏的具体实现通过操作所附加源代码的抽象语法树(AST),生成一棵新的树,这棵树可以插入到被附加的类/结构体/方法等内部,也可以放在其旁边。整个过程完全集成在编译器中,因此生成的代码与手写代码被同等对待,享有同样的编译器优化,并无缝融入构建流程。凭借这些性能优化以及基于结构和语义而非纯文本的代码转换能力,宏在生成样板代码方面极其强大。