<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Leonardo Cardoso on Medium]]></title>
        <description><![CDATA[Stories by Leonardo Cardoso on Medium]]></description>
        <link>https://medium.com/@leocardz?source=rss-4f741db0316e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5J58m3_kIYMnjMQHrduJSQ.png</url>
            <title>Stories by Leonardo Cardoso on Medium</title>
            <link>https://medium.com/@leocardz?source=rss-4f741db0316e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 05:35:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@leocardz/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Create Swift Macros: The Easiest and Least Boring Way]]></title>
            <link>https://engineering.traderepublic.com/how-to-create-swift-macros-the-easiest-and-least-boring-way-faf1113c6194?source=rss-4f741db0316e------2</link>
            <guid isPermaLink="false">https://medium.com/p/faf1113c6194</guid>
            <category><![CDATA[testing-tools]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[swift-macros]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Leonardo Cardoso]]></dc:creator>
            <pubDate>Tue, 10 Jun 2025 06:02:11 GMT</pubDate>
            <atom:updated>2025-06-10T06:02:11.767Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the second part of my <a href="https://traderepublic.substack.com/p/get-ready-for-swift-macros">previous blog post </a>about Swift Macros. In this one, you’ll learn how to create your own macro from scratch, simple and straightforward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hA8K5RKFvKa8-R1FrxniXg.png" /></figure><p>Before we dive in, let’s quickly go over why you’d even want to create a macro in the first place. We’ve been working on a macro library for mocks, which we’re currently using and refining internally. By the way, it’ll be open-sourced <em>soonish</em>, so stay tuned!</p><p>We decided to tackle mocks because our previous setup, using the amazing <a href="https://github.com/krzysztofzablocki/Sourcery">Sourcery</a>, while functional, relied heavily on code generation using external tools like Stencil and YAML. On top of that, we had to manage the generated files through separate testing packages. This was necessary because, when using those mocks as dependencies, we only needed to include the testing package itself.</p><p>The macro-based approach we built replicates what our Sourcery integration used to do, but in a way that speeds up adoption internally and minimizes the amount of required changes. It helped us cut down over <strong>18,000+ lines of code</strong> in the first few commits alone, just by migrating from the old codegen setup. Since it’s written entirely in Swift, engineers no longer have to fiddle with extra config files or manually update mocks. The setup is much cleaner now, which means better productivity and fewer headaches. Plus, with fewer module dependencies, the overall architecture is much simpler too and the compilation times have improved as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B9QKeYm2yZI4ObKZ.png" /></figure><h3>Understanding the Best Role For You</h3><p>First of all, you need to figure out what kind of macro you want to create. There are 7 macro roles in Swift, divided into 2 main categories: <strong>freestanding</strong> and <strong>attached</strong>. They’re pretty straightforward. Here’s a quick overview:</p><h3>Freestanding Macros</h3><p>These are used in places where you just call the macro directly, kind of like functions or attributes. They can exist by themselves.</p><ul><li><strong>Expression Macros (#expression)</strong>: These macros generate expressions. For example, replacing force-unwrapped URLs with a safer, compile-time-checked version.</li><li><strong>Declaration Macros (#declaration)</strong>: These macros generate new declarations, such as creating a Swift model from a JSON string.</li></ul><h3>Attached Macros</h3><p>These are macros that attach to existing declarations (like types, functions, or variables) using the @ symbol.</p><ul><li><strong>Member Macros (@member)</strong>: Add new declarations within the entity they’re attached to, like generating public initializers for a struct.</li><li><strong>Member Attribute Macros (@memberAttribute)</strong>: Attach attributes to declarations, modifying properties or methods with metadata or compiler directives.</li><li><strong>Extension Macros (@extension)</strong>: Add code at the same level as the original entity, allowing you to append functionalities without cluttering the primary definition.</li><li><strong>Peer Macros (@peer)</strong>: Similar to extension macros but create new entities at the same level, useful for generating mock structures.</li><li><strong>Accessor Macros (@accessor)</strong>: Generate accessors for properties, converting stored properties into computed ones.</li></ul><h3>Writing the Macro</h3><p>Learning how to write a macro comes with a bit of a learning curve, but once you get the hang of it, it becomes way simpler. You might even start thinking in macros!</p><p>So, first things first: you’ll need to create a package for your macro. Fortunately, Xcode provides a built-in template you can use to bootstrap your project quickly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R2SXN2JyKgoNC_rL.png" /></figure><p>The template already includes a very simple freestanding expression macro. It returns both a value and a string representing the original source code.</p><p>A macro in Swift needs two packages: one for the declaration and one for the implementation. In the default template, the declaration lives in the MyFirstMacro folder, and the implementation is in MyFirstMacroMacros.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ty1ydt4jknSfregD.png" /></figure><p>If we take a look at the Package.swift, it’s clearly defined:</p><pre>targets: [<br>  .macro(<br>      name: &quot;MyFirstMacroMacros&quot;,<br>      dependencies: [<br>          .product(name: &quot;SwiftSyntaxMacros&quot;, package: &quot;swift-syntax&quot;),<br>          .product(name: &quot;SwiftCompilerPlugin&quot;, package: &quot;swift-syntax&quot;)<br>      ]<br>  ),<br>  .target(name: &quot;MyFirstMacro&quot;, dependencies: [&quot;MyFirstMacroMacros&quot;]),<br>  .executableTarget(name: &quot;MyFirstMacroClient&quot;, dependencies: [&quot;MyFirstMacro&quot;]),<br>  .testTarget(<br>      name: &quot;MyFirstMacroTests&quot;,<br>      dependencies: [<br>          &quot;MyFirstMacroMacros&quot;,<br>          .product(name: &quot;SwiftSyntaxMacrosTestSupport&quot;, package: &quot;swift-syntax&quot;),<br>      ]<br>  ),<br>]</pre><p>Having this default setup is great to get started quickly, but that’s not what we’re aiming for here. Instead, we’re going to implement our own macro that automatically generates a public initializer for public entities.</p><h3>Bootstrapping our Macro</h3><p>Let’s start by creating a barebones macro. To do that, we’ll need to create <strong>two files</strong>:</p><ol><li><strong>Macro Declaration</strong> — This lives in the library package. Let’s name it InitifyMacro.swift.</li><li><strong>Macro Implementation</strong> — This goes in the macro implementation target. We’ll call this file InitifyMacroImplementation.swift.</li></ol><p>Now that we’ve got two empty files, it’s time to add some actual code.</p><p>Since we want to generate an initializer inside the scope of the struct or class, our InitifyMacro will be an <strong>attached member macro</strong>.</p><pre>@attached(member)<br>public macro Initify() = #externalMacro(<br>  module: &quot;MyFirstMacroMacros&quot;,<br>  type: &quot;InitifyMacro&quot;<br>)</pre><p>Once the declaration is defined, we can move on to the implementation, starting with just the declaration itself. In InitifyMacroImplementation.swift, let’s add the following:</p><pre>import SwiftCompilerPlugin<br>import SwiftSyntax<br>import SwiftSyntaxBuilder<br>import SwiftSyntaxMacros</pre><pre>public struct InitifyMacro: MemberMacro {<br>    public static func expansion(<br>        of node: AttributeSyntax,<br>        providingMembersOf declaration: some DeclGroupSyntax,<br>        in context: some MacroExpansionContext<br>    ) throws -&gt; [DeclSyntax] {<br>        []<br>    }<br>}</pre><p>Lastly, we need to update, or create, the <strong>Compiler Plugin export</strong>. This step is required to register your code as a macro so Swift knows about it.</p><pre>import SwiftCompilerPlugin<br>import SwiftSyntaxMacros</pre><pre>@main<br>struct MyFirstMacroPlugin: CompilerPlugin {<br>    let providingMacros: [Macro.Type] = [<br>        InitifyMacro.self,<br>    ]<br>}</pre><p>At this point, if you apply the @Initify macro to any entity, nothing will happen. So let’s move on and write the internals of the macro to actually generate some code.</p><h3>TDD for the Win</h3><p>There’s a lot of back and forth in macro development, so using TDD is hands down the best way to write and update your macros. Seriously, it’ll save you time, reduce bugs, and make your macro logic way easier to maintain as it grows.</p><p>And, interestingly enough, testing in Swift Macros relies on comparing strings. That’s right! But it’s a bit more involved than it sounds.</p><p>We use a special assertion called #assertMacroExpansion, which compares the original source code to the expected result after the macro is expanded. It also provides helpful hints when something in the expansion fails, making debugging way easier.</p><p>So, let’s create a test file to try it out with a simple example:</p><pre>#if canImport(MyFirstMacroMacros)<br>import SwiftSyntax<br>import SwiftSyntaxBuilder<br>import SwiftSyntaxMacros<br>import SwiftSyntaxMacrosTestSupport<br>import XCTest<br><br>import MyFirstMacroMacros<br><br>let testMacros: [String: Macro.Type] = [<br>    &quot;Initify&quot;: InitifyMacro.self,<br>]<br><br>final class MyFirstMacroTests: XCTestCase {<br>    func testMacro() throws {<br>        assertMacroExpansion(<br>            &quot;&quot;&quot;<br>            @Initify<br>            public struct Card {<br>                let rank: Rank<br>                let suit: String<br>                let value: Int<br>            }<br>            &quot;&quot;&quot;,<br>            expandedSource: &quot;&quot;&quot;<br>            public struct Card {<br>                let rank: Rank<br>                let suit: String<br>                let value: Int<br>            <br>                public init(rank: Rank, suit: String, value: Int) {<br>                    self.rank = rank<br>                    self.suit = suit<br>                    self.value = value<br>                }<br>            }<br>            &quot;&quot;&quot;,<br>            macros: testMacros<br>        )<br>    }<br>}<br>#endif</pre><p>If we run this test right now… it’ll fail! And that’s totally expected. Our macro is still not generating anything yet. But the beauty of it is that the failing test, as seen below, tells us exactly what’s missing between the lines 6-10. That’s one step closer to fully understanding how our macro works. Enter: SwiftSyntax.</p><pre>failed - Macro expansion did not produce the expected expanded source<br> public struct Card {<br>     let rank: Rank<br>     let suit: String<br>     let value: Int<br>–    public init(rank: Rank, suit: String, value: Int) {<br>–        self.rank = rank<br>–        self.suit = suit<br>–        self.value = value<br>–    }<br> }</pre><h3>SwiftSyntax and The Tree Representation</h3><p>SwiftSyntax (<a href="https://github.com/swiftlang/swift-syntax">REF</a>) is the library that powers macro development. It’s what generates the syntax tree representation of Swift code. It’s basically a structured map of everything: declarations, variables, parameters, functions, and more. With it, we can inspect this tree like an X-Ray, that will help us figure out exactly what we need to write to make our macro do its job.</p><p>If we head over to the InitifyMacro in InitifyMacroImplementation.swift and dump the declaration, here’s what we get:</p><pre>...<br>) throws -&gt; [DeclSyntax] {<br>    dump(declaration)<br>    return []<br>}<br>...</pre><pre>- StructDeclSyntax<br>├─attributes: AttributeListSyntax<br>│ ╰─[0]: AttributeSyntax<br>│   ├─atSign: atSign<br>│   ╰─attributeName: IdentifierTypeSyntax<br>│     ╰─name: identifier(&quot;Initify&quot;)<br>├─modifiers: DeclModifierListSyntax<br>│ ╰─[0]: DeclModifierSyntax<br>│   ╰─name: keyword(SwiftSyntax.Keyword.public)<br>├─structKeyword: keyword(SwiftSyntax.Keyword.struct)<br>├─name: identifier(&quot;Card&quot;)<br>╰─memberBlock: MemberBlockSyntax<br>  ├─leftBrace: leftBrace<br>  ├─members: MemberBlockItemListSyntax<br>  │ ├─[0]: MemberBlockItemSyntax<br>  │ │ ╰─decl: VariableDeclSyntax<br>  │ │   ├─attributes: AttributeListSyntax<br>  │ │   ├─modifiers: DeclModifierListSyntax<br>  │ │   ├─bindingSpecifier: keyword(SwiftSyntax.Keyword.let)<br>  │ │   ╰─bindings: PatternBindingListSyntax<br>  │ │     ╰─[0]: PatternBindingSyntax<br>  │ │       ├─pattern: IdentifierPatternSyntax<br>  │ │       │ ╰─identifier: identifier(&quot;rank&quot;)<br>  │ │       ╰─typeAnnotation: TypeAnnotationSyntax<br>  │ │         ├─colon: colon<br>  │ │         ╰─type: IdentifierTypeSyntax<br>  │ │           ╰─name: identifier(&quot;Rank&quot;)<br>  │ ├─[1]: MemberBlockItemSyntax<br>  │ │ ╰─decl: VariableDeclSyntax<br>  │ │   ├─attributes: AttributeListSyntax<br>  │ │   ├─modifiers: DeclModifierListSyntax<br>  │ │   ├─bindingSpecifier: keyword(SwiftSyntax.Keyword.let)<br>  │ │   ╰─bindings: PatternBindingListSyntax<br>  │ │     ╰─[0]: PatternBindingSyntax<br>  │ │       ├─pattern: IdentifierPatternSyntax<br>  │ │       │ ╰─identifier: identifier(&quot;suit&quot;)<br>  │ │       ╰─typeAnnotation: TypeAnnotationSyntax<br>  │ │         ├─colon: colon<br>  │ │         ╰─type: IdentifierTypeSyntax<br>  │ │           ╰─name: identifier(&quot;String&quot;)<br>  │ ╰─[2]: MemberBlockItemSyntax<br>  │   ╰─decl: VariableDeclSyntax<br>  │     ├─attributes: AttributeListSyntax<br>  │     ├─modifiers: DeclModifierListSyntax<br>  │     ├─bindingSpecifier: keyword(SwiftSyntax.Keyword.let)<br>  │     ╰─bindings: PatternBindingListSyntax<br>  │       ╰─[0]: PatternBindingSyntax<br>  │         ├─pattern: IdentifierPatternSyntax<br>  │         │ ╰─identifier: identifier(&quot;value&quot;)<br>  │         ╰─typeAnnotation: TypeAnnotationSyntax<br>  │           ├─colon: colon<br>  │           ╰─type: IdentifierTypeSyntax<br>  │             ╰─name: identifier(&quot;Int&quot;)<br>  ╰─rightBrace: rightBrace</pre><p>That’s the full structure of our Card entity, and the types ending with Syntax are classes inside the SwiftSyntax library. Since we want to generate an initializer for its properties and I can see the properties are inside something called memberBlock, I know that’s the right spot I need to go to extract the data and directives for building the initializer.</p><p>And here comes the magic…</p><p>I know where the properties are, but I don’t yet know which SwiftSyntax types or builders to use to generate them.</p><p>The trick is just go to your test, add the part of the code you expect to be generated directly in the <strong>original source code</strong>, and run the test again. The dump output reveals what you need to build.</p><p>It’s like the compiler is giving you a to-do list. Just follow the breadcrumbs.</p><pre>assertMacroExpansion(<br>    &quot;&quot;&quot;<br>    @Initify<br>    public struct Card {<br>        let rank: Rank<br>        let suit: String<br>        let value: Int<br>    <br>        public init(rank: Rank, suit: String, value: Int) {<br>            self.rank = rank<br>            self.suit = suit<br>            self.value = value<br>        }<br>    }<br>    &quot;&quot;&quot;,<br>    ...<br>)</pre><p>We notice that there’s a new item of the type InitializerDeclSyntax in the output.</p><pre>│ ╰─[3]: MemberBlockItemSyntax<br>│   ╰─decl: InitializerDeclSyntax<br>│     ├─attributes: AttributeListSyntax<br>│     ├─modifiers: DeclModifierListSyntax<br>│     │ ╰─[0]: DeclModifierSyntax<br>│     │   ╰─name: keyword(SwiftSyntax.Keyword.public)<br>│     ├─initKeyword: keyword(SwiftSyntax.Keyword.init)<br>│     ├─signature: FunctionSignatureSyntax<br>│     │ ╰─parameterClause: FunctionParameterClauseSyntax<br>│     │   ├─leftParen: leftParen<br>│     │   ├─parameters: FunctionParameterListSyntax<br>│     │   │ ├─[0]: FunctionParameterSyntax<br>│     │   │ │ ├─attributes: AttributeListSyntax<br>│     │   │ │ ├─modifiers: DeclModifierListSyntax<br>│     │   │ │ ├─firstName: identifier(&quot;rank&quot;)<br>│     │   │ │ ├─colon: colon<br>│     │   │ │ ├─type: IdentifierTypeSyntax<br>│     │   │ │ │ ╰─name: identifier(&quot;Rank&quot;)<br>│     │   │ │ ╰─trailingComma: comma<br>│     │   │ ├─[1]: FunctionParameterSyntax<br>│     │   │ │ ├─attributes: AttributeListSyntax<br>│     │   │ │ ├─modifiers: DeclModifierListSyntax<br>│     │   │ │ ├─firstName: identifier(&quot;suit&quot;)<br>│     │   │ │ ├─colon: colon<br>│     │   │ │ ├─type: IdentifierTypeSyntax<br>│     │   │ │ │ ╰─name: identifier(&quot;String&quot;)<br>│     │   │ │ ╰─trailingComma: comma<br>│     │   │ ╰─[2]: FunctionParameterSyntax<br>│     │   │   ├─attributes: AttributeListSyntax<br>│     │   │   ├─modifiers: DeclModifierListSyntax<br>│     │   │   ├─firstName: identifier(&quot;value&quot;)<br>│     │   │   ├─colon: colon<br>│     │   │   ╰─type: IdentifierTypeSyntax<br>│     │   │     ╰─name: identifier(&quot;Int&quot;)<br>│     │   ╰─rightParen: rightParen<br>│     ╰─body: CodeBlockSyntax<br>│       ├─leftBrace: leftBrace<br>│       ├─statements: CodeBlockItemListSyntax<br>│       │ ├─[0]: CodeBlockItemSyntax<br>│       │ │ ╰─item: SequenceExprSyntax<br>│       │ │   ╰─elements: ExprListSyntax<br>│       │ │     ├─[0]: MemberAccessExprSyntax<br>│       │ │     │ ├─base: DeclReferenceExprSyntax<br>│       │ │     │ │ ╰─baseName: keyword(SwiftSyntax.Keyword.self)<br>│       │ │     │ ├─period: period<br>│       │ │     │ ╰─declName: DeclReferenceExprSyntax<br>│       │ │     │   ╰─baseName: identifier(&quot;rank&quot;)<br>│       │ │     ├─[1]: AssignmentExprSyntax<br>│       │ │     │ ╰─equal: equal<br>│       │ │     ╰─[2]: DeclReferenceExprSyntax<br>│       │ │       ╰─baseName: identifier(&quot;rank&quot;)<br>│       │ ├─[1]: CodeBlockItemSyntax<br>│       │ │ ╰─item: SequenceExprSyntax<br>│       │ │   ╰─elements: ExprListSyntax<br>│       │ │     ├─[0]: MemberAccessExprSyntax<br>│       │ │     │ ├─base: DeclReferenceExprSyntax<br>│       │ │     │ │ ╰─baseName: keyword(SwiftSyntax.Keyword.self)<br>│       │ │     │ ├─period: period<br>│       │ │     │ ╰─declName: DeclReferenceExprSyntax<br>│       │ │     │   ╰─baseName: identifier(&quot;suit&quot;)<br>│       │ │     ├─[1]: AssignmentExprSyntax<br>│       │ │     │ ╰─equal: equal<br>│       │ │     ╰─[2]: DeclReferenceExprSyntax<br>│       │ │       ╰─baseName: identifier(&quot;suit&quot;)<br>│       │ ╰─[2]: CodeBlockItemSyntax<br>│       │   ╰─item: SequenceExprSyntax<br>│       │     ╰─elements: ExprListSyntax<br>│       │       ├─[0]: MemberAccessExprSyntax<br>│       │       │ ├─base: DeclReferenceExprSyntax<br>│       │       │ │ ╰─baseName: keyword(SwiftSyntax.Keyword.self)<br>│       │       │ ├─period: period<br>│       │       │ ╰─declName: DeclReferenceExprSyntax<br>│       │       │   ╰─baseName: identifier(&quot;value&quot;)<br>│       │       ├─[1]: AssignmentExprSyntax<br>│       │       │ ╰─equal: equal<br>│       │       ╰─[2]: DeclReferenceExprSyntax<br>│       │         ╰─baseName: identifier(&quot;value&quot;)<br>│       ╰─rightBrace: rightBrace<br>╰─rightBrace: rightBrace</pre><p>Now we’re all set.</p><p>We know what we need to build, we know where to look to generate the initializer, and we’re ready to write the actual code.</p><p>Now let’s just go back to our macro declaration and add the names parameter to the annotation. The value named(init) will tell the compiler that this macro needs to be evaluated at the initializer phase.</p><pre>@attached(member, names: named(init))<br>public macro Initify() = #externalMacro(<br>  module: &quot;MyFirstMacroMacros&quot;,<br>  type: &quot;InitifyMacro&quot;<br>)</pre><p>Let’s put it all together and bring our @Initify macro to life!</p><h3>Cooking the @Initify Macro.</h3><p>First, we need to get the list of members from the entity.</p><p>In our case, we know the entity is a struct, so we can cast the declaration as a StructDeclSyntax. Once we do that, we can access its memberBlock to get the members. If you dump the members, you’ll see a slice of the original syntax tree.</p><pre>) throws -&gt; [DeclSyntax] {<br>    guard let structDecl = declaration.as(StructDeclSyntax.self) else { return [] }<br>    let members = structDecl.memberBlock.members<br>    dump(members)<br>    return []<br>}</pre><p>Now we need to create a new instance of the InitializerDeclSyntax and pass the new members and create its body.</p><p>Let’s convert the members into parameters by analyzing the tree representations. This is the code:</p><pre>let memberAsFunctionParameters: [FunctionParameterSyntax] = members.compactMap { member -&gt; FunctionParameterSyntax? in<br>    guard<br>        let decl = member.decl.as(VariableDeclSyntax.self),<br>        let binding = decl.bindings.first,<br>        let name = binding.pattern.as(IdentifierPatternSyntax.self),<br>        let type = binding.typeAnnotation?.type<br>    else { return nil }<br>    // rank: Rank<br>    return FunctionParameterSyntax(<br>        firstName: name.identifier,<br>        type: type<br>    )<br>}</pre><p>Now we also need to convert them into assignments to go in the initializer body:</p><pre>let memberAsCodeBlockItems: [SequenceExprSyntax] = members.compactMap { member -&gt; SequenceExprSyntax? in<br>    guard<br>        let decl = member.decl.as(VariableDeclSyntax.self),<br>        let binding = decl.bindings.first,<br>        let name = binding.pattern.as(IdentifierPatternSyntax.self)<br>    else { return nil }<br>    return SequenceExprSyntax(<br>        elements: ExprListSyntax {<br>            // self.rank<br>            MemberAccessExprSyntax(<br>                base: DeclReferenceExprSyntax(baseName: TokenSyntax.keyword(.self)),<br>                declName: DeclReferenceExprSyntax(baseName: name.identifier.trimmed)<br>            )<br><br>            // =<br>            AssignmentExprSyntax()<br><br>            // rank<br>            DeclReferenceExprSyntax(baseName: name.identifier.trimmed)<br>        }<br>    )<br>}</pre><p>And let’s now apply them to the initializer:</p><pre>let initializerDeclSyntax = InitializerDeclSyntax(<br>    modifiers: DeclModifierListSyntax {<br>        DeclModifierSyntax(name: TokenSyntax.keyword(.public))<br>    },<br>    signature: FunctionSignatureSyntax(<br>        parameterClause: FunctionParameterClauseSyntax {<br>            memberAsFunctionParameters<br>        }<br>    ),<br>    body: CodeBlockSyntax(<br>        statements: CodeBlockItemListSyntax {<br>            memberAsCodeBlockItems<br>        }<br>    )<br>)<br><br>return [DeclSyntax(initializerDeclSyntax)]</pre><p>Our macro is finally done! If you run the tests now… they’ll pass!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4lqn_CRh1L9QzxewIQcgyQ.gif" /></figure><h3>Wrapping Up</h3><p>And that’s it! You’ve learned how to create your own macro, understand its types, and explore the context using the syntax tree. Powerful stuff, but we’re just getting started.</p><p>Remember, this is only your first macro. The syntax tree gives you access to everything: variables, functions, parameters, extensions, you name it. It’s all there. And you can also pass parameters in the macro itself, e.g. for default values. You just have to dive in and explore.</p><p>Swift Macros can seriously level up your tooling. Once you get the hang of them, they’ll start to feel like a natural extension of how you write code.</p><p>Got questions or feedback? Drop a comment or reach out, I’d love to hear what you’re building with Swift Macros!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=faf1113c6194" width="1" height="1" alt=""><hr><p><a href="https://engineering.traderepublic.com/how-to-create-swift-macros-the-easiest-and-least-boring-way-faf1113c6194">How to Create Swift Macros: The Easiest and Least Boring Way</a> was originally published in <a href="https://engineering.traderepublic.com/">Trade Republic Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get Ready for Swift Macros]]></title>
            <link>https://engineering.traderepublic.com/get-ready-for-swift-macros-fe21d3867e02?source=rss-4f741db0316e------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe21d3867e02</guid>
            <category><![CDATA[macro]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Leonardo Cardoso]]></dc:creator>
            <pubDate>Mon, 23 Oct 2023 13:46:41 GMT</pubDate>
            <atom:updated>2023-11-06T09:59:42.771Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ELlfzixo-HF_T4zvKJNh3Q.png" /></figure><p>Swift Macros were announced at this year’s WWDC. The moment I saw them, I instantly recognized a significant shift: there would be a time before Swift Macros and a time after Swift Macros. In fact, several newly announced powerful features in the new versions of Apple’s operating systems, such as <strong>@Observable</strong>, <strong>#Preview</strong> and <strong>@Model</strong>, are macros.</p><p>You might be asking, “What’s so special about them?”</p><p><strong>tl;dr:</strong> They make code cleaner, reduce lines of code, and expedite feature implementation. All of that while keeping debugging and type safety in place.</p><p>Let’s get familiar with the innovative mechanics of Swift Macros and explore how to leverage their capabilities.</p><p>This is a two-part series. In the first article, we’ll introduce what Swift Macros are, exploring key topics like their roles and names, examining potential limitations, and concluding with insights into how the iOS Team at Trade Republic plans to utilize them. In the second article, we’ll dive into the technical implementation, showcasing how to write and test Swift Macros, along with a guide to best practices.</p><h3>What It Is</h3><p>Swift Macros are a groundbreaking way for generating boilerplate code and performing other compile-time operations. The phrase “compile-time” is crucial here because unlike other methods and without the need of running scripts, Swift Macros generate code during the project’s compilation, offering immediate availability.</p><p>Macros in Swift have an additive nature, meaning they can create new code, but they won’t alter or remove existing parts. This includes built-in safety checks, ensuring that the code entering and exiting the macro complies with Swift’s syntax, and that the types of values used align properly.</p><p>When you utilize a macro in your code, it often means concealing extra code that the macro symbolizes, but that just doesn’t need to be visible all the time. Conveniently, Xcode allows you to expand or collapse this generated code as desired.</p><p>If an error occurs during macro expansion, it’s treated as a compilation error by the compiler. These safeguards simplify the use of macros, aiding in correct use and timely identification of any issues.</p><h3>How It Works</h3><p>First, take note that a Macro is composed of two key elements: Definition and Implementation. These two separate parts must be located in different modules. The rationale behind this is that when your code triggers a macro, the Swift compiler identifies this call and directs it to a specialized compiler plug-in, where the logic of the macro resides.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*V05ICjU0loeLZpHY0kAKSg.png" /></figure><p>The Swift compiler incorporates this expansion into your program, compiling both your original code and the newly-added expansion. When you run the application, it operates as though you had written the expansion manually.</p><h3>Roles</h3><p>Understanding the roles of Swift Macros is essential; it’s the key to selecting the most suitable one for your specific needs. In essence, these roles dictate where the code will be generated and how the compiler will treat the generated code. There are seven distinct roles, grouped into two categories as we will see below.</p><p>Before we go the the categories, we need to have in mind that when setting up a macro, several guidelines come into play: you’ll need to specify the category, identify the role, and — if applicable — configure role-specific settings. On top of this, attaching the <strong>macro</strong> keyword is a must, and remember that macros can accept arguments and, some, return types.</p><p>For instance, here’s what a macro definition looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*BkS_M654Bjxrh70bePIAfQ.png" /></figure><h4>Freestanding Macros</h4><p>The first category is named <strong>freestanding</strong> macros and their symbol is the pound sign <strong>‘#’</strong>. These macros are self-sufficient, with their generated code positioned exactly where it was defined. In this category, there are two roles: <strong>#expression</strong> and <strong>#declaration</strong> macros.</p><h4>#expression</h4><p>Expression macros have the capability to transform and expand source code by executing flexible syntax adjustments on their parameters to achieve the intended output.</p><p>To illustrate, consider the scenario where the goal is to replace all instances of force-unwrapped URLs with a well-tested URL macro, designed for situations where the URL’s existence is guaranteed. This can be done by an expression macro.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oVY9sVxFJLM-5fmqEuK43g.png" /></figure><p>This comes in particularly handy when you have a lint tool in place that frowns upon force-unwrapping. In fact, we’ve successfully managed to do away with the need for force-unwrapping altogether.</p><h4>#declaration</h4><p>This macro operates similarly to the Expression macro, but it diverges in that it can’t return a type. A concrete example of a declaration macro is one that regenerates a JSON string into a corresponding Swift model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*AP5D5TBC19ry0BP2T51fBQ.png" /></figure><h4>Attached Macros</h4><p>The second category is known as <strong>attached</strong> macros and is identified by the <strong>‘@’</strong> symbol. Unlike their freestanding counterparts, attached macros need an associated entity for code generation. Within this category, you’ll find five distinct roles: <strong>@member</strong>, <strong>@memberAttribute</strong>, <strong>@extension</strong>, <strong>@peer</strong>, and <strong>@accessor</strong>. These macros are versatile and can be applied to a wide range of entities, including methods, structs, classes, extensions.</p><h4>@member</h4><p>Member macros serve to amplify the entity to which they’re applied by creating code, new declarations, within that very entity. To give you a concrete example, let’s say you want default initializers for each property in a struct. A Member macro would be your go-to solution for this task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d9VWyDGlNbpo7hl6wVPgjg.png" /></figure><p>Macros give us comprehensive insights into the entity, from the accessor control right down to the type. This allows us to tailor the output as needed.</p><h4>@memberAttribute</h4><p>Member Attribute macros are designed to attach attributes to declarations in the type or extension where they are implemented. This functionality enables you to modify the properties or methods in your code through metadata or specific compiler directives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*WYfXHG4qOK-OENzIQdmV8w.png" /></figure><h4>@extension</h4><p>Extension Macros add code at the same level as the original entity. Imagine being able to append necessary functionalities to a class or struct without cluttering its primary definition. This type offers this level of cleanliness, keeping your main entity definitions concise while still affording you the flexibility to add as much functionality as needed. Check the example below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IGF8Vo5ktUzdC-eWTBdyKw.png" /></figure><h4>@peer</h4><p>The Peer Macro closely mirrors the Extension macro in appearance, placing the generated code at the same level as the original entity and offering the same degree of flexibility in terms of adding new code. However, there’s a key difference: the Peer Macro actually creates a new entity. This makes it an ideal choice for generating mock structures, for instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xzF9_OjdXbyQVFih4U4Djg.png" /></figure><h4>@accessor</h4><p>An Accessor macro serves the purpose of generating accessors for a given property, thereby converting what was initially a stored property into a computed one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*U_1xF8QYVaFA2ANPxwOvrA.png" /></figure><h3>Arguments</h3><p>Some macros offer configurable settings to fine-tune the code generation. These settings typically fall into two categories: <strong>Names</strong> and <strong>Conformances</strong>.</p><h4>Names</h4><p>Macros can add declarations based on the names specified in this argument. Since these names are predetermined, they become instantly accessible in the generated code. This is applicable to various elements like properties, methods, option sets, and enumeration cases. The names argument is not limited to one, allowing you to specify multiple names for greater flexibility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lVmmO5ZAE77s6sAz7o6P6Q.png" /></figure><p>Further customization is available through specifiers such as <strong>overloaded</strong>, <strong>named(*)</strong>, <strong>prefixed(*)</strong>, <strong>suffixed(*)</strong>, and <strong>arbitrary</strong>.</p><ul><li><strong>overloaded</strong>: For declarations that use the specified name as their base name.</li><li><strong>named</strong>: For declarations with a specific, fixed name.</li><li><strong>prefixed</strong> and <strong>suffixed</strong>: For declarations that include a particular prefix or suffix.</li><li><strong>arbitrary</strong>: For declarations that don’t fit into the other categories.</li></ul><h4>Conformance</h4><p>In the context of Extension macros, the <strong>conformances</strong> argument is essential when that extension is conforming to a protocol because it ensures that it is recognized by the compiler as such.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*RSnF_UyD2FOVcoJtBJY7Zw.png" /></figure><h3>What It Can and Cannot See</h3><h4>Scope</h4><p>It’s crucial to understand that macros are limited to the scope of the entity to which they are applied; they can’t access anything outside of that scope. For example, if you apply a macro to a protocol that inherits from another protocol, the parent protocol remains inaccessible.</p><h4>Availability</h4><p>The code generated by one macro isn’t accessible to another macro during the compilation stage. For instance, if one macro generates initializers, those can’t serve as parameter values for another macro.</p><h4>Constraints</h4><p>Some macros may demand explicit code, even when your own macro can generate that very code. To illustrate, let’s revisit the example of a macro that creates initializers. If you apply a new <strong>@Model</strong> macro, it will still require the implementation of an initializer.</p><h3>Considerations</h3><h4>Type Safety</h4><p>Swift Macros upholds the language’s commitment to type safety. Even though macros interpret everything ultimately as strings, they allow for the input of parameters using their original types. It’s important, however, to be mindful of where you place your macro definitions. At the same time, they need visibility of the relevant structures and prevent cyclic dependencies. Here’s a pro tip: a macro can be internal to any package, but its implementation must reside in a separate module as explained before, so you can use it as leverage to only expose modules to other packages when needed.</p><h4>Difference from Property Wrappers</h4><p>You might be inclined to think that Macros and property wrappers serve the same purpose, especially because they look quite similar at a glance. However, they operate at different phases of the development cycle.</p><p>Property wrappers come into play at runtime, dynamically interacting with your wrapped values by applying any added logic you’ve programmed. In contrast, Macros operate strictly at compile-time, enriching your codebase before your application even starts running.</p><h4>Caching</h4><p>After a Macro’s code is compiled and the new elements are added, that code stays put until you perform a full build again. If you decide to change your Macro code, it won’t update automatically because it’s cached. This caching mechanism helps to eliminate redundant builds, making the development process more efficient.</p><h4>Boilerplate</h4><p>In the topic of Boilerplate, there are two ways for writing macros, which we’ll explore in more detail in the second part of this article. A small spoiler: you can either craft macros as extensive strings or use a more type-safe approach with the objects provided by Swift Syntax. The latter is generally preferred, but it can be a bit unwieldy due to the potential size of the code blocks. However, it offers the advantage of minimizing boilerplate code in the long run. So, if you’re writing a macro that may not eliminate much repetitive code now, it could pay off in the future.</p><h3>Conclusion (and How We Plan to Utilize Swift Macros)</h3><p>Our codebase is robust, maintained by a talented team of nearly 30 iOS engineers. One of our first applications for Swift Macros is to replace our current mock generator, which is responsible for creating close to 1,000 files and approximately 120,000 lines of code.</p><p>Going forward, we aim to broaden the use of Macros in our testing stack. Specifically, we plan to replace manually created Entity Builders that help us in writing tests, among other enhancements.</p><p>In conclusion, the adoption of Swift Macros promises to be a game-changer for our development processes. Not only will it streamline the way we generate code, but it will also enhance the modularity and reusability of our codebase, allowing the engineers to focus on building more complex and creative solutions.</p><h3>Further Content</h3><ul><li><a href="https://github.com/apple/swift-evolution/blob/main/proposals/0389-attached-macros.md">Attached Macro Proposal</a></li><li><a href="https://github.com/apple/swift-evolution/blob/main/proposals/0397-freestanding-declaration-macros.md">Freestanding Macro Proposal</a></li><li><a href="https://developer.apple.com/wwdc23/10166">WWDC23: Write Swift Macros</a></li><li><a href="https://developer.apple.com/wwdc23/10167">WWDC23: Expand on Swift Macros</a></li><li><a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/macros/">Macro Post at swift.org</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe21d3867e02" width="1" height="1" alt=""><hr><p><a href="https://engineering.traderepublic.com/get-ready-for-swift-macros-fe21d3867e02">Get Ready for Swift Macros</a> was originally published in <a href="https://engineering.traderepublic.com/">Trade Republic Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>