<?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 Esraa Eid on Medium]]></title>
        <description><![CDATA[Stories by Esraa Eid on Medium]]></description>
        <link>https://medium.com/@esraa-eid?source=rss-3fcc7f428b42------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*l2_9uYixmEw023xcp_lQrw.jpeg</url>
            <title>Stories by Esraa Eid on Medium</title>
            <link>https://medium.com/@esraa-eid?source=rss-3fcc7f428b42------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 06:33:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@esraa-eid/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[A Guide to Generating Swift Code with Swift Syntax and Swift OpenAPI (Part 2)]]></title>
            <link>https://medium.com/deloitte-uk-cloud-blog/a-guide-to-generating-swift-code-with-swift-syntax-and-swift-openapi-part-2-c277388ad38c?source=rss-3fcc7f428b42------2</link>
            <guid isPermaLink="false">https://medium.com/p/c277388ad38c</guid>
            <category><![CDATA[code-generation]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Esraa Eid]]></dc:creator>
            <pubDate>Thu, 09 Oct 2025 10:02:09 GMT</pubDate>
            <atom:updated>2026-05-18T08:45:22.319Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="#6933"><strong>About the song.</strong></a><a href="#69e2"><strong><br>Recap &amp; What’s Ahead.</strong></a><a href="#461a"><strong><br>Approach 2: Swift Syntax.<br></strong></a><a href="#8ba9"><strong>Approach 3: Swift OpenAPI Generator.<br></strong></a><a href="#98ab"><strong>Conclusion</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*sqFyD4b2ZRykQ5rm2ozIUQ.png" /></figure><p><em>The following section contains a short cultural story about the song “Al-Atlal” by Umm Kulthum. If you’re not interested in this topic, feel free to skip it.</em></p><h3>About the song</h3><p>There’s something hauntingly eternal about <em>Al-Atlal </em>(The Ruins), a song that turns heartbreak into a sacred ritual. Based on poetry by Ibrahim Nagi, <em>Al-Atlal</em> was composed by Riad Al Sunbati and released at a time when the Arab world was mourning collective losses.<br> But the magic? Umm Kulthum turned a poem of ruin into a hymn of resilience. Audiences say she didn’t just sing this song, she <em>lived</em> it on stage, often closing her eyes and waving her hand as if conjuring spirits.<br> The line, “Give me my freedom, set my hands free,” became an anthem of emotional emancipation, quoted by revolutionaries, lovers, and poets alike.<br> I chose this song because it reminds us that from ruins, beauty can still rise and sometimes, the deepest griefs are the most universal.</p><p>Thank you for taking a moment to discover this cultural gem with me. I’d love to hear your thoughts if it resonates with you, too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*Lh6pJ8n9kpYenP0gzSEm8Q.png" /></figure><h3>Recap &amp; What’s Ahead</h3><p>In <a href="https://medium.com/deloitte-uk-cloud-blog/a-guide-to-generating-swift-code-with-swift-mustache-part-1-d985711e2c2c"><strong>Part One</strong></a>, we explored the foundations of Swift code generation, covering how templating with <strong>Swift Mustache</strong> can help generate simple Swift structs from JSON Schema.</p><p>Now in <strong>Part Two</strong>, we’ll level up with more powerful tools: <strong>SwiftSyntax</strong>, which provides deep control over Swift’s abstract syntax trees, and <strong>Swift OpenAPI Generator</strong>, which lets you generate Swift code from OpenAPI specs.</p><p>Keep Umm Kulthum <a href="https://www.youtube.com/watch?v=VsZReSJ5AU8">playing in the background</a>, and let’s dive in! 🎶</p><h3>Approach 2: Swift Syntax</h3><blockquote><a href="https://github.com/apple/swift-syntax">SwiftSyntax</a> is a powerful tool that enables developers to programmatically generate Swift source code by building syntax trees.</blockquote><h4>What is a Syntax Tree?</h4><p>A Syntax Tree, or an Abstract Syntax Tree (AST), is a structured representation of Swift source code. It breaks the code into smaller syntax nodes, each representing a fundamental part of the Swift language, such as keywords, expressions, statements, and declarations.</p><p>Think of it as Swift code turned into a Lego set: each piece (node) fits into a specific spot to form the complete picture.</p><h4>Defining Swift Code Using a Syntax Tree</h4><p>To visualize this, try the <a href="https://swift-ast-explorer.com/">Swift AST Explorer</a>:</p><p>1- Open the tool.</p><p>2- Type a simple Swift struct like this:</p><pre>struct User {<br>    let id: Int<br>    let name: String<br>}</pre><p>The <strong>Swift AST Explorer</strong> will generate a structured representation of this code, showing how Swift breaks it down into syntax nodes.</p><pre>SourceFile<br> ├─ StructDecl (struct User)<br> │   ├─ Identifier (User)<br> │   ├─ MemberDeclBlock<br> │       ├─ VariableDecl (let id: Int)<br> │       ├─ VariableDecl (let name: String)</pre><p>Each node corresponds to a part of the code, and SwiftSyntax allows you to build, modify, and manipulate these nodes.</p><p>To visualize this, try the<a href="https://swift-ast-explorer.com/"> Swift AST Explorer:</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BhY76X8W_H3XIQSZK4DPzQ.png" /></figure><h4>How Does SwiftSyntax Work?</h4><p>Instead of using string-based templates like Mustache. SwiftSyntax offers an accurate tree-based model of Swift source code, empowering Swift tools to parse, inspect, generate, and transform Swift source code using structured syntax defined in <a href="https://github.com/apple/swift-syntax/tree/main/Sources/SwiftSyntax">SwiftSyntax</a> and <a href="https://github.com/apple/swift-syntax/tree/main/Sources/SwiftSyntaxBuilder">SwiftSyntaxBuilder</a>, with support from Swift <a href="https://swift-ast-explorer.com/">AST</a> Explorer.</p><p><strong>Example Generating a Struct with SwiftSyntax</strong></p><pre>func generateStruct(name: String, properties: [(String, String)]) -&gt; DeclSyntax {<br>    let propertiesSyntax = properties.map { &quot;let \($0): \($1)&quot; }.joined(separator: &quot;\n&quot;)<br>    return DeclSyntax(&quot;&quot;&quot;<br>        struct \(name): Codable {<br>            \(propertiesSyntax)<br>        }<br>    &quot;&quot;&quot;)<br>}</pre><p><strong>Generated Swift Code</strong></p><pre>struct Person: Codable {<br>    let name: String<br>    let age: Int<br>}</pre><h4>Integrating SwiftSyntax in <a href="https://github.com/esraaeiid/SwiftCodeGenerator">Your Project</a></h4><p>Now that we understand the basics, let’s implement it within the<a href="https://github.com/esraaeiid/SwiftCodeGenerator/tree/main/Sources"> SwiftCodeGenerator</a> repository:</p><p>1. Add SwiftSyntax Dependency</p><p>In Package.swift:</p><pre>let package = Package( <br>   name: &quot;SwiftGenerator&quot;, <br>   platforms: [ <br>     .macOS(.v12) <br> ], <br>   products: [ <br>    .executable( <br>            name: &quot;SwiftGeneratorExecutable&quot;, <br>            targets: [&quot;SwiftGeneratorExecutable&quot;] <br>        ), <br>    <br>   .library( <br>        name: &quot;SwiftGenerator&quot;, <br>        targets: [&quot;SwiftGenerator&quot;]), <br>   ], <br>   dependencies: [ <br> // Swift Syntax: Apple&#39;s official library for parsing and generating Swift code<br>    .package(url: &quot;https://github.com/hummingbird-project/hummingbird-mustache.git&quot;, from: &quot;1.0.3&quot;), <br>    .package(url: &quot;https://github.com/apple/swift-syntax.git&quot;, from: &quot;510.0.2&quot;), <br>   ], <br>   targets: [ <br>    .target(name: &quot;SwiftGenerator&quot; , dependencies: [ <br>        .product(name: &quot;HummingbirdMustache&quot;, package: &quot;hummingbird-mustache&quot;), <br>// Swift code parsing and generation<br>        .product(name: &quot;SwiftSyntax&quot;, package: &quot;swift-syntax&quot;), <br>        .product(name: &quot;SwiftSyntaxBuilder&quot;, package: &quot;swift-syntax&quot;), <br>    ]), <br>    .executableTarget( <br>        name: &quot;SwiftGeneratorExecutable&quot;, <br>        dependencies: [ <br>            .byName(name: &quot;SwiftGenerator&quot;), <br>        ] <br>    ), <br>    .testTarget( <br>        name: &quot;SwiftGeneratorTests&quot;, <br>        dependencies: [&quot;SwiftGenerator&quot;] <br>    ), <br>   ] <br>) </pre><p>2. Create SwiftSyntaxGenerator.swift</p><p>In Sources/SwiftGenerator/SwiftSyntax, create SwiftSyntaxGenerator.swift <br>This file will contain the logic responsible for building Swift code using <strong>SwiftSyntax</strong>, which allows us to programmatically define Swift struct (like struct Person) by assembling syntax components instead of writing raw strings. Paste the following code into it:</p><pre>import SwiftSyntax<br>import SwiftSyntaxBuilder<br>import Foundation<br>public enum SwiftSyntaxGenerator { <br>   static func generateStructSyntax(name: String, properties: [(String, String)]) -&gt; DeclSyntax { <br>    let structDecl = StructDeclSyntax( <br>        modifiers: DeclModifierListSyntax { <br>            DeclModifierSyntax(name: .keyword(.public)) // Marks the struct as public <br>        }, <br>        name: TokenSyntax(stringLiteral: name), // The name of the struct <br>        inheritanceClause: InheritanceClauseSyntax { <br>            InheritedTypeSyntax(type: TypeSyntax(&quot;Codable&quot;)) // Adds Codable conformance <br>        } <br>    ) { <br>        for (propertyName, propertyType) in properties { <br>            VariableDeclSyntax(bindingSpecifier: .keyword(.let)) { // Declares a constant property <br>                PatternBindingSyntax( <br>                    pattern: IdentifierPatternSyntax(identifier: .identifier(propertyName)), // Property name <br>                    typeAnnotation: TypeAnnotationSyntax(type: IdentifierTypeSyntax(name: .identifier(propertyType))) // Property type <br>                ) <br>            } <br>        } <br>    } <br>    .with(\.leadingTrivia, .newlines(1)) // Adds a newline before the <br>    .with(\.trailingTrivia, .newlines(1)) // Adds a newline after the <br> <br>    return DeclSyntax(structDecl) <br>   } <br>} </pre><p>If you’re unfamiliar with syntax trees or want to understand what these building blocks represent, you can explore the<a href="https://swift-ast-explorer.com/"> Swift AST Explorer</a> or check out the<a href="https://github.com/apple/swift-syntax"> SwiftSyntax documentation.</a></p><p>In the SwiftSyntaxGenerator.swift file, add a new function to trigger SwiftSyntax-based generation:</p><pre>public struct SwiftGenerator { <br>   public init() {} <br> <br>   //MARK: - Swift Syntax <br>   public func generateWithSwiftSyntax() { <br>           // These values represent the properties of the actual Swift struct to generate <br>   let generatedSyntax = SwiftSyntaxGenerator.generateStructSyntax(name: &quot;User&quot;, properties: [(&quot;id&quot;, &quot;Int&quot;), (&quot;name&quot;, &quot;String&quot;)]) <br>    print(generatedSyntax) <br>   } <br>} </pre><p>Call the function from the main executable file.</p><pre>import SwiftGenerator<br>let generator = SwiftGenerator ()<br>generator.generateWithSwiftSyntax()</pre><p>Then run the project in the terminal using:</p><pre>swift run</pre><p><strong>Note:</strong> The terminal output may not automatically include spaces. To fix this, <strong>Trivia</strong> has been added to SwiftSyntax to format the structure properly.</p><pre>struct User: Codable {<br>let id: Int<br>let name: String<br>let email: String<br>}</pre><h4>Let’s now extend our implementation to support optional and array types.</h4><p>Inside SwiftSyntaxGenerator.swift, define a helper function to resolve optional and array inside the struct:</p><pre>// Define a public enum to encapsulate the SwiftSyntax generation logic <br>public enum SwiftSyntaxGenerator { <br> // Main function to generate a Swift struct syntax <br> <br>   static func generateStructSyntax(name: String, properties: [(String, String)]) -&gt; DeclSyntax { <br>// Define the structure declaration <br>    let structDecl = StructDeclSyntax( <br>// Add a &#39;public&#39; access modifier <br>        modifiers: [.init(name: .keyword(.public))], <br>// Add &#39;struct&#39; keyword explicitly <br>        structKeyword: .keyword(.struct), <br> // Name of the struct <br>        name: .identifier(name), <br>// Add inheritance clause (e.g., Codable) <br>        inheritanceClause: InheritanceClauseSyntax { <br>            InheritedTypeListSyntax { <br>                InheritedTypeSyntax(type: TypeSyntax(&quot;Codable&quot;)) <br>            } <br>           }, <br>// Define the member block of the struct (its properties) <br>        memberBlock: MemberBlockSyntax { <br>            for (propertyName, propertyType) in properties { <br>  // Declare each property as &#39;let&#39; <br>                VariableDeclSyntax(bindingSpecifier: .keyword(.let)) { <br>// Create the binding: name and type <br>                    PatternBindingSyntax( <br>                        pattern: IdentifierPatternSyntax(identifier: .identifier(propertyName)), <br>  // Add the type annotation, resolved dynamically <br>                        typeAnnotation: TypeAnnotationSyntax( <br>                            type: resolveType(propertyType) <br>                        ) <br>                    ) <br>                } <br>            } <br>        } <br>       ) <br>// Return the complete DeclSyntax representing the struct <br>    return DeclSyntax(structDecl) <br>   } </pre><pre>// Helper function to handle optional and array types from string format <br>private static func resolveType(_ typeString: String) -&gt; TypeSyntax { <br>// Check if the type ends with &#39;?&#39;, indicating an optional <br>    if typeString.hasSuffix(&quot;?&quot;) { <br>        let baseType = String(typeString.dropLast()) // remove &#39;?&#39; <br>        return TypeSyntax(OptionalTypeSyntax(wrappedType: TypeSyntax(stringLiteral: baseType))) <br>   // Check if the type starts with &#39;[&#39; and ends with &#39;]&#39;, indicating an array <br>    } else if typeString.hasPrefix(&quot;[&quot;) &amp;&amp; typeString.hasSuffix(&quot;]&quot;) { <br>        let elementType = String(typeString.dropFirst().dropLast()) <br>        return TypeSyntax(ArrayTypeSyntax(element: TypeSyntax(stringLiteral: elementType))) <br>// Otherwise, it&#39;s just a regular type (e.g., String, Int) <br>       } else { <br>        return TypeSyntax(stringLiteral: typeString) <br>    } <br>   } <br>} </pre><p>In the SwiftGenerator.swift file, edit the function to look like the following:</p><pre>//MARK: - Swift Syntax<br>    public func generateWithSwiftSyntax() {<br>        <br>        let generatedSyntax = SwiftSyntaxGenerator.generateStructSyntax(<br>            name: &quot;Person&quot;,<br>            properties: [<br>                (&quot;name&quot;, &quot;String?&quot;),<br>                (&quot;age&quot;, &quot;[Int]&quot;),<br>                (&quot;email&quot;, &quot;String&quot;)<br>            ]<br>        )<br>        print(generatedSyntax)<br>    }</pre><p>swift run and Voila! You should see the generated structure printed on the terminal:</p><pre>public struct Person: Codable {<br>    let name: String?<br>    let age: [Int]<br>    let email: String<br>}</pre><p><strong>Pro Tip:</strong> To improve readability, instead of printing the output in the terminal, try writing it to a file.</p><h4>Writing to a File &amp; Using Structs with SwiftSyntax</h4><p>To improve readability and reusability, instead of printing the output directly to the terminal, let’s write the generated code to a file.</p><p><strong>Step 1: Define a Property Model for SwiftSyntax:</strong></p><p>In <strong>Sources/SwiftGenerator/Model</strong>, create a new file named SwiftSyntaxPropert.swift and add the following:</p><pre>import Foundation<br>// MARK: - Swift Syntax Property Model<br>/// Represents a property in a Swift struct with type information<br>/// This model is used by the SwiftSyntax generator to define struct properties<br>/// with support for optional types, arrays, and various Swift type mappings<br>public struct SwiftSyntaxProperty {<br>    let name: String<br>    let type: String<br>    let isOptional: Bool<br>    let isArray: Bool<br>    <br>    /// Initialize a SwiftSyntaxProperty with basic type information<br>    /// - Parameters:<br>    ///   - name: The property name (e.g., &quot;id&quot;, &quot;name&quot;, &quot;email&quot;)<br>    ///   - type: The Swift type (e.g., &quot;String&quot;, &quot;Int&quot;, &quot;UUID&quot;)<br>    ///   - isOptional: Whether the property is optional (default: false)<br>    ///   - isArray: Whether the property is an array (default: false)<br>    public init(name: String, type: String, isOptional: Bool = false, isArray: Bool = false) {<br>        self.name = name<br>        self.type = type<br>        self.isOptional = isOptional<br>        self.isArray = isArray<br>    }<br>    <br>    /// Convenience initializer for optional properties<br>    /// - Parameters:<br>    ///   - name: The property name<br>    ///   - type: The Swift type<br>    /// - Returns: A SwiftSyntaxProperty with isOptional set to true<br>    public static func optional(_ name: String, type: String) -&gt; SwiftSyntaxProperty {<br>        return SwiftSyntaxProperty(name: name, type: type, isOptional: true)<br>    }<br>    <br>    /// Convenience initializer for array properties<br>    /// - Parameters:<br>    ///   - name: The property name<br>    ///   - type: The Swift type (element type of the array)<br>    /// - Returns: A SwiftSyntaxProperty with isArray set to true<br>    public static func array(_ name: String, type: String) -&gt; SwiftSyntaxProperty {<br>        return SwiftSyntaxProperty(name: name, type: type, isArray: true)<br>    }<br>    <br>    /// Convenience initializer for optional array properties<br>    /// - Parameters:<br>    ///   - name: The property name<br>    ///   - type: The Swift type (element type of the array)<br>    /// - Returns: A SwiftSyntaxProperty with both isOptional and isArray set to true<br>    public static func optionalArray(_ name: String, type: String) -&gt; SwiftSyntaxProperty {<br>        return SwiftSyntaxProperty(name: name, type: type, isOptional: true, isArray: true)<br>    }<br>}</pre><p>This struct allows you to express whether a property is optional, an array, or both.</p><p><strong>Step 2: Update </strong>SwiftSyntaxGenerator.swift</p><p>Next, update the generator logic to use SwiftSyntaxProperty:</p><ul><li>Convert each property into a VariableDeclSyntax.</li></ul><pre>/// Generates Swift structs using Apple&#39;s SwiftSyntax library<br>/// This provides programmatic control over Swift code generation<br>public enum SwiftSyntaxGenerator {<br>    <br>    /// Generates Swift struct syntax from a name and array of properties<br>    /// - Parameters:<br>    ///   - name: The name of the struct to generate<br>    ///   - properties: Array of SwiftSyntaxProperty objects defining the struct properties<br>    /// - Returns: Generated Swift struct as DeclSyntax<br>    static func generateStructSyntax(name: String, properties: [SwiftSyntaxProperty]) -&gt; DeclSyntax {<br>        let structDecl = StructDeclSyntax(<br>            modifiers: [.init(name: .keyword(.public))],<br>            structKeyword: .keyword(.struct),<br>            name: .identifier(name),<br>            inheritanceClause: InheritanceClauseSyntax {<br>                InheritedTypeListSyntax {<br>                    InheritedTypeSyntax(type: TypeSyntax(&quot;Codable&quot;))<br>                }<br>            },<br>            memberBlock: MemberBlockSyntax {<br>                for property in properties {<br>                    VariableDeclSyntax(bindingSpecifier: .keyword(.let)) {<br>                        PatternBindingSyntax(<br>                            pattern: IdentifierPatternSyntax(identifier: .identifier(property.name)),<br>                            typeAnnotation: TypeAnnotationSyntax(<br>                                type: resolveType(from: property)<br>                            )<br>                        )<br>                    }<br>                }<br>            }<br>        )<br>        return DeclSyntax(structDecl)<br>    }<br>    <br>}</pre><ul><li>Use a helper method resolveType()to handle optional and array types.</li></ul><pre>/// Resolves Swift type from property information<br>    /// - Parameter property: SwiftSyntaxProperty containing type information<br>    /// - Returns: TypeSyntax representing the Swift type<br>    private static func resolveType(from property: SwiftSyntaxProperty) -&gt; TypeSyntax {<br>        var baseType = property.type<br>        <br>        // Handle array types<br>        if property.isArray {<br>            baseType = &quot;[\(baseType)]&quot;<br>        }<br>        <br>        // Handle optional types<br>        if property.isOptional {<br>            return TypeSyntax(OptionalTypeSyntax(wrappedType: TypeSyntax(stringLiteral: baseType)))<br>        } else {<br>            return TypeSyntax(stringLiteral: baseType)<br>        }<br>    }</pre><ul><li>Add a method to write the result to a file.</li></ul><pre>/// Generates Swift struct and writes it to a file<br>    /// - Parameters:<br>    ///   - name: The name of the struct to generate<br>    ///   - properties: Array of SwiftSyntaxProperty objects<br>    ///   - filename: Name of the file to create (defaults to struct name + &quot;.swift&quot;)<br>    ///   - directory: Directory to save the file (defaults to &quot;Generated&quot;)<br>    /// - Throws: File system errors if writing fails<br>    static func generateStructFile(<br>        name: String, <br>        properties: [SwiftSyntaxProperty], <br>        filename: String? = nil,<br>        directory: String = &quot;Generated&quot;<br>    ) throws {<br>        let generatedSyntax = generateStructSyntax(name: name, properties: properties)<br>        let swiftCode = generatedSyntax.formatted().description<br>        <br>        let fileManager = FileManager.default<br>        let currentDirectory = fileManager.currentDirectoryPath<br>        let outputDirectory = &quot;\(currentDirectory)/\(directory)&quot;<br>        <br>        // Create directory if it doesn&#39;t exist<br>        if !fileManager.fileExists(atPath: outputDirectory) {<br>            try fileManager.createDirectory(atPath: outputDirectory, withIntermediateDirectories: true)<br>        }<br>        <br>        // Use provided filename or default to struct name<br>        let finalFilename = filename ?? &quot;\(name).swift&quot;<br>        let filePath = &quot;\(outputDirectory)/\(finalFilename)&quot;<br>        <br>        try swiftCode.write(toFile: filePath, atomically: true, encoding: .utf8)<br>        print(&quot;Generated SwiftSyntax file: \(filePath)&quot;)<br>    }<br>    <br>    <br>    /// Legacy method for backward compatibility<br>    /// - Parameters:<br>    ///   - name: Struct name<br>    ///   - properties: Array of (name, type) tuples<br>    /// - Returns: Generated Swift struct as DeclSyntax<br>    static func generateStructSyntax(name: String, properties: [(String, String)]) -&gt; DeclSyntax {<br>        // Convert tuple array to SwiftSyntaxProperty array<br>        let swiftProperties = properties.map { (name, type) in<br>            SwiftSyntaxProperty(name: name, type: type)<br>        }<br>        return generateStructSyntax(name: name, properties: swiftProperties)<br>    }</pre><pre>// MARK: - Convenience Methods<br>extension SwiftSyntaxGenerator {<br>    /// Generate a Person struct with common properties<br>    static func generatePersonStruct() throws {<br>        let properties = [<br>            SwiftSyntaxProperty(name: &quot;id&quot;, type: &quot;UUID&quot;),<br>            SwiftSyntaxProperty.optional(&quot;firstName&quot;, type: &quot;String&quot;),<br>            SwiftSyntaxProperty.optional(&quot;lastName&quot;, type: &quot;String&quot;),<br>            SwiftSyntaxProperty.array(&quot;phoneNumbers&quot;, type: &quot;String&quot;),<br>            SwiftSyntaxProperty(name: &quot;age&quot;, type: &quot;Int&quot;),<br>            SwiftSyntaxProperty.optional(&quot;email&quot;, type: &quot;String&quot;)<br>        ]<br>        <br>        try generateStructFile(name: &quot;Person&quot;, properties: properties)<br>    }<br>    <br>    /// Generate a Product struct with typical e-commerce properties<br>    static func generateProductStruct() throws {<br>        let properties = [<br>            SwiftSyntaxProperty(name: &quot;id&quot;, type: &quot;UUID&quot;),<br>            SwiftSyntaxProperty(name: &quot;name&quot;, type: &quot;String&quot;),<br>            SwiftSyntaxProperty.optional(&quot;description&quot;, type: &quot;String&quot;),<br>            SwiftSyntaxProperty(name: &quot;price&quot;, type: &quot;Double&quot;),<br>            SwiftSyntaxProperty.array(&quot;tags&quot;, type: &quot;String&quot;),<br>            SwiftSyntaxProperty.optional(&quot;imageURL&quot;, type: &quot;String&quot;),<br>            SwiftSyntaxProperty(name: &quot;inStock&quot;, type: &quot;Bool&quot;)<br>        ]<br>        <br>        try generateStructFile(name: &quot;Product&quot;, properties: properties)<br>    }</pre><p><strong>Step 3: Use the Generator in Your Main Logic<br></strong>In SwiftSyntaxGenerator.swift, call the generator with a list of SwiftSyntaxProperty, you can also reuse the previous file-writing helper if you want consistent handling:</p><pre>  //MARK: - Swift Syntax<br>    public func generateWithSwiftSyntax() {<br>        <br>        // Create properties using the new SwiftSyntaxProperty model<br>        let properties = [<br>            SwiftSyntaxProperty(name: &quot;id&quot;, type: &quot;UUID&quot;),<br>            SwiftSyntaxProperty.optional(&quot;name&quot;, type: &quot;String&quot;),<br>            SwiftSyntaxProperty.array(&quot;emails&quot;, type: &quot;String&quot;),<br>            SwiftSyntaxProperty(name: &quot;age&quot;, type: &quot;Int&quot;),<br>            SwiftSyntaxProperty.optional(&quot;phoneNumber&quot;, type: &quot;String&quot;)<br>        ]<br>        <br>        do {<br>            // Generate and write to file using the new method<br>            try SwiftSyntaxGenerator.generateStructFile(<br>                name: &quot;Person&quot;,<br>                properties: properties,<br>                filename: &quot;Person.swift&quot;<br>            )<br>        } catch {<br>            print(&quot;Error generating SwiftSyntax file: \(error)&quot;)<br>        }<br>    }<br>    <br>    // MARK: - Swift Syntax with Shared File Helper<br>    /// Generates Swift struct using SwiftSyntax and writes to file using shared helper<br>    public func generateSwiftSyntaxWithSharedHelper() {<br>        let properties = [<br>            SwiftSyntaxProperty(name: &quot;id&quot;, type: &quot;UUID&quot;),<br>            SwiftSyntaxProperty.optional(&quot;name&quot;, type: &quot;String&quot;),<br>            SwiftSyntaxProperty.array(&quot;emails&quot;, type: &quot;String&quot;),<br>            SwiftSyntaxProperty(name: &quot;age&quot;, type: &quot;Int&quot;),<br>            SwiftSyntaxProperty.optional(&quot;phoneNumber&quot;, type: &quot;String&quot;)<br>        ]<br>        <br>        // Generate Swift code using SwiftSyntax<br>        let generatedSyntax = SwiftSyntaxGenerator.generateStructSyntax(<br>            name: &quot;Person&quot;,<br>            properties: properties<br>        )<br>        let swiftCode = generatedSyntax.formatted().description<br>        <br>        // Write using shared file helper for consistency<br>        do {<br>            try writeToFile(swiftCode, filename: &quot;PersonWithHelper.swift&quot;)<br>        } catch {<br>            print(&quot;Error writing SwiftSyntax file: \(error)&quot;)<br>        }<br>    }</pre><p>swift run and Voila! You can see the Generated directory with Person.swift and PersonWithHelper.swift files inside:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*wuFLOoTXd1nQ6KrUK1JLUw.png" /></figure><p><strong>Step 4: Batch Struct Generation</strong></p><p>Finally, if you want to generate multiple models at once (e.g. Person, Product), create a convenience method:</p><pre>// MARK: - Batch Generation<br>    /// Generates multiple structs at once using different approaches<br>    public func generateAllStructs() {<br>        print(&quot;Starting batch code generation...&quot;)<br>        <br>        // Generate using Mustache templates<br>        generateWithSwiftMustache()<br>        <br>        // Generate using SwiftSyntax<br>        generateWithSwiftSyntax()<br>        <br>        // Generate predefined structs<br>        do {<br>            try SwiftSyntaxGenerator.generatePersonStruct()<br>            try SwiftSyntaxGenerator.generateProductStruct()<br>        } catch {<br>            print(&quot; Error generating predefined structs: \(error)&quot;)<br>        }<br>        <br>        print(&quot;Batch generation completed!&quot;)<br>    }</pre><p><strong>Final Hierarchy &amp; Output</strong></p><p>After running the command swift run you’ll find your generated files under a Generated folder like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*zb_b0llfaofSrwZAbnqp3g.png" /></figure><h4>Other Use Cases for SwiftSyntax</h4><p><strong><em>Code Formatting and Linting</em></strong></p><p>SwiftSyntax powers tools like <strong>SwiftFormat</strong> and <strong>SwiftLint</strong>, which analyze and enforce coding style.</p><h4>Benefits of SwiftSyntax</h4><ul><li>Easy composition and reusability of Swift code structures.</li><li>It integrates with swift-parser and swift-format, ensuring compatibility and consistency in Swift code generation.</li><li>SwiftSyntaxBuilder that provides powerful tools for constructing and manipulating Swift syntax trees.</li><li>The <a href="https://swift-ast-explorer.com/">Swift AST Explorer</a> has proven invaluable for comprehending the hierarchical structure required for generating Swift code.</li><li>Enhancing flexibility and type safety in Swift models as It supports defining optional keys and enums with raw values for coding keys, also enable the creation of model objects with custom initializers crucial for decoding and initializing Swift objects from external representations.</li></ul><h4>Challenges of using SwiftSyntax</h4><ul><li>Requires careful planning and understanding of Swift’s syntax and semantics.</li><li>According to discussions in <a href="https://forums.swift.org/t/announcing-swiftsyntaxbuilder/56565/6">this thread</a>, generating functions or control statements using SwiftSyntaxBuilder may require additional effort and attention to detail. However it could be managed with <a href="https://github.com/sebsto/swift-aws-lambda-sam-dsl/blob/22ba8e864ac67ea2bcb3164828c0a064f8298495/Sources/AWSLambdaDeploymentDescriptorGeneratorSwiftSyntax/SwiftDeploymentDescriptorGenerator.swift#L51">swift-syntax</a>.</li><li>There is a lack of comprehensive documentation that effectively showcases Swift Syntax Builder. However, there are numerous <a href="https://github.com/apple/swift-syntax/tree/main/Tests/SwiftSyntaxBuilderTest">test cases</a> for Swift Syntax Builder that cover a wide range of syntax examples.</li><li>Occasionally, debugging SwiftSyntax may present challenges such as vague error messages like “The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions” that doesn’t represent the real error.</li></ul><p>For additional resources, explore <a href="https://github.com/apple/swift-syntax/tree/main/Tests/SwiftSyntaxBuilderTest">SwiftSyntax Examples</a>.</p><h3>Approach 3: Swift OpenAPI Generator</h3><blockquote>The <strong>OpenAPI specification</strong> is a standardized way to describe RESTful APIs, from endpoints to request and response formats, usually written in <strong>YAML</strong> or <strong>JSON</strong>.</blockquote><blockquote>The <a href="https://github.com/apple/swift-openapi-generator"><strong>Swift OpenAPI Generator</strong></a> takes these OpenAPI specs and generates Swift code that represents API models, clients, or servers.</blockquote><h4>What Is OpenAPI?</h4><p>Think of OpenAPI as a <strong>rulebook</strong> for describing APIs. It defines how endpoints behave, the structure of requests/responses, parameters, and data types.</p><p>Here’s an example of a simple OpenAPI YAML describing a GET /users endpoint:</p><pre>openapi: 3.0.0<br>info:<br>  title: User API<br>  version: 1.0.0<br>paths:<br>  /users:<br>    get:<br>      summary: Get all users<br>      responses:<br>        200:<br>          description: A list of users<br>          content:<br>            application/json:<br>              schema:<br>                type: array<br>                items:<br>                  type: object<br>                  properties:<br>                    id:<br>                      type: integer<br>                    name:<br>                      type: string</pre><h4>How it works?</h4><p>The Swift OpenAPI Generator reads your OpenAPI spec and translates it into Swift models that mirror the defined schema. It also handles networking layers (if configured).</p><p><strong>Example Generating Swift Code based on </strong><a href="https://github.com/sebsto/swift-aws-lambda-sam-dsl/blob/22ba8e864ac67ea2bcb3164828c0a064f8298495/Sources/AWSLambdaDeploymentDescriptorGeneratorOpenAPI/openapi.yaml"><strong>yaml</strong></a><strong> provided:</strong></p><pre>components:<br>  schemas:<br>    Person:<br>      type: object<br>      properties:<br>        name:<br>          type: string<br>        age:<br>          type: integer</pre><p><strong>Generated Swift Code:</strong></p><pre>struct Person: Codable {<br>    let name: String<br>    let age: Int<br>}</pre><h4>Let’s Integrate It in <a href="https://github.com/esraaeiid/SwiftCodeGenerator">Our Project</a></h4><p>1- Add the Swift OpenAPI Generator to your Package.swift:</p><pre>// swift-tools-version: 6.0<br><br>import PackageDescription<br><br>let package = Package(<br>    name: &quot;SwiftGenerator&quot;,<br>    <br>    platforms: [<br>         .macOS(.v12) <br>     ],<br>    <br>    products: [<br>        .executable(<br>                name: &quot;SwiftGeneratorExecutable&quot;,<br>                targets: [&quot;SwiftGeneratorExecutable&quot;]<br>            ),<br>        <br>        .library(<br>            name: &quot;SwiftGenerator&quot;,<br>            targets: [&quot;SwiftGenerator&quot;]),<br>    ],<br>    <br>    dependencies: [<br>        .package(url: &quot;https://github.com/hummingbird-project/hummingbird-mustache.git&quot;, from: &quot;1.0.3&quot;),<br>        <br>        .package(url: &quot;https://github.com/apple/swift-syntax.git&quot;, from: &quot;510.0.2&quot;),<br>        <br>        // OpenAPI Generator: Generate Swift code from OpenAPI specifications<br>        .package(url: &quot;https://github.com/apple/swift-openapi-generator&quot;, from: &quot;1.0.0&quot;),<br>        <br>        // OpenAPI Runtime: Runtime support for OpenAPI-generated code<br>        .package(url: &quot;https://github.com/apple/swift-openapi-runtime&quot;, from: &quot;1.0.0&quot;),<br>        <br>        // OpenAPI URLSession: HTTP client integration for OpenAPI<br>        .package(url: &quot;https://github.com/apple/swift-openapi-urlsession&quot;, from: &quot;1.0.0&quot;),<br>    ],<br>    <br>    targets: [<br>        .target(name: &quot;SwiftGenerator&quot; , dependencies: [<br>            .product(name: &quot;HummingbirdMustache&quot;, package: &quot;hummingbird-mustache&quot;),<br>            <br>            .product(name: &quot;SwiftSyntax&quot;, package: &quot;swift-syntax&quot;),<br>            .product(name: &quot;SwiftSyntaxBuilder&quot;, package: &quot;swift-syntax&quot;),<br>            <br>            // OpenAPI integration for API-driven code generation<br>            .product(name: &quot;OpenAPIGenerator&quot;, package: &quot;swift-openapi-generator&quot;),<br>            .product(name: &quot;OpenAPIRuntime&quot;, package: &quot;swift-openapi-runtime&quot;),<br>            .product(name: &quot;OpenAPIURLSession&quot;, package: &quot;swift-openapi-urlsession&quot;),<br>        ]),<br>        <br>        .executableTarget(<br>            name: &quot;SwiftGeneratorExecutable&quot;,<br>            dependencies: [<br>                .byName(name: &quot;SwiftGenerator&quot;),<br>            ]<br>        ),<br>        <br>        .testTarget(<br>            name: &quot;SwiftGeneratorTests&quot;,<br>            dependencies: [&quot;SwiftGenerator&quot;]<br>        ),<br>    ]<br>)</pre><p>2- Create the required files inside your target folder:</p><p>openapi.yaml: This file holds your OpenAPI specification.</p><pre>openapi: 3.0.0<br>info:<br>  title: Example API<br>  version: 1.0.0<br>paths:<br>  /users:<br>    get:<br>      summary: Fetch users<br>      responses:<br>        200:<br>          description: A list of users<br>          content:<br>            application/json:<br>              schema:<br>                type: array<br>                items:<br>                  type: object<br>                  properties:<br>                    id:<br>                      type: integer<br>                    name:<br>                      type: string</pre><p>openapi-generator-config.yaml: This file contains optional configurations. You can start with default values for now.</p><pre>generate:<br>  - types<br>  - client</pre><p>3- Run the Generator</p><pre>swift run</pre><p>You will find a path to generated files like this:</p><figure><img alt="Terminal window showing the output of running SwiftGenerator, including configuration details, output file names (Types.swift, Client.swift), and output directory path." src="https://cdn-images-1.medium.com/max/1024/1*mxBYWjOX5_9nePWXTRuNxQ.png" /></figure><p>Tip: Use Cmd + Shift + . in Finder to reveal hidden folders like .build.</p><figure><img alt="Finder window showing the ‘GeneratedSources’ folder containing three Swift files: Client.swift, Server.swift, and Types.swift." src="https://cdn-images-1.medium.com/max/848/1*UFrpKc5XTMEnvAys59WKOA.png" /></figure><h4>Where’s the Customization?</h4><p>You might now be wondering, Can I customize the formatting like I did with SwiftSyntax or SwiftMustache?</p><p>Unfortunately, <strong>not really</strong>. That’s not what OpenAPI Generator is built for.</p><p>Here’s why:</p><ul><li>Swift OpenAPI Generator follows a <strong>strict structure</strong> defined by the OpenAPI specification.</li><li>It’s <strong>meant to be automatic and deterministic</strong>, not custom-crafted.</li><li>It <strong>doesn’t provide an API for adjusting formatting or trivia</strong> (spaces, newlines).</li></ul><p>So, generating a custom-looking struct like this:</p><pre>public struct Person: Codable {<br>    let name: String?<br>    let age: [Int]<br>    let email: String<br>}</pre><p>is <strong>not feasible</strong>, because:</p><p>Swift OpenAPI Generator <strong>doesn’t offer the same level of fine-grained control over formatting</strong> like SwiftSyntax does, because it’s not a general-purpose code generator. It’s a <strong>spec-driven tool</strong> designed to <strong>generate models and HTTP clients/servers</strong> from OpenAPI specs.</p><h4>Benefits of Swift OpenAPI:</h4><ul><li>Already built and maintained by Apple.</li><li>Saves time by auto-generating code from API specs.</li><li>Follows best practices for Swift model and networking code.</li></ul><h4>Challenges of using Swift OpenAPI:</h4><ul><li>Limited flexibility, it won’t suit use cases needing full customization.</li><li>Struggles with <strong>deeply nested JSON</strong>, <strong>functions</strong>, or <strong>enum edge cases</strong>.</li><li>Can’t control formatting like spacing or newlines.</li></ul><p>For more details, check out the <a href="https://swiftpackageindex.com/apple/swift-openapi-generator/1.2.1/documentation/swift-openapi-generator">Swift OpenAPI Generator Documentation</a>.</p><h3>Conclusion</h3><p>After evaluating these three approaches, I found <strong>SwiftSyntax</strong> to be the most suitable for generating Swift code from JSON Schema due to its precision and compiler compatibility. However, each approach has its strengths depending on the use case:</p><ul><li><strong>Use Mustache</strong> if you need quick, template-based code generation.</li><li><strong>Use SwiftSyntax</strong> if you need precise, structured, and compiler-friendly code.</li><li><strong>Use OpenAPI</strong> if you’re working with API specifications.</li></ul><p>This project has deepened my understanding of code generation in Swift, and I hope this article helps others exploring similar challenges.</p><h4>Have you used any code generation tools in Swift?</h4><p>I’d love to hear your thoughts, which approach do you prefer? Are there other tools you’re biased toward? Let’s share knowledge and learn from each other!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c277388ad38c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/deloitte-uk-cloud-blog/a-guide-to-generating-swift-code-with-swift-syntax-and-swift-openapi-part-2-c277388ad38c">A Guide to Generating Swift Code with Swift Syntax and Swift OpenAPI (Part 2)</a> was originally published in <a href="https://medium.com/deloitte-uk-cloud-blog">Deloitte UK Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Guide to Generating Swift Code with Swift Mustache (Part 1)]]></title>
            <link>https://medium.com/deloitte-uk-cloud-blog/a-guide-to-generating-swift-code-with-swift-mustache-part-1-d985711e2c2c?source=rss-3fcc7f428b42------2</link>
            <guid isPermaLink="false">https://medium.com/p/d985711e2c2c</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[code-generation]]></category>
            <dc:creator><![CDATA[Esraa Eid]]></dc:creator>
            <pubDate>Tue, 07 Oct 2025 10:11:01 GMT</pubDate>
            <atom:updated>2025-10-09T10:05:37.465Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="#af6c"><strong>About the song. </strong></a><br><a href="#24af"><strong>Can Swift code generate Swift code? </strong></a><br><a href="#4269"><strong>Approach 1: Swift Mustache.</strong></a><strong><br></strong><a href="#dd19"><strong>Conclusion (to Part 1!)</strong></a></p><figure><img alt="An album cover for “Enta Omri” by Umm Kulthum, one of the most famous Arabic songs of all time. This is a classic design from an era when Umm Kulthum’s music was distributed on cassette tapes and vinyl records." src="https://cdn-images-1.medium.com/max/1024/1*Kb82hONft6TblQByXiK5AA.png" /></figure><p><em>The following section contains a short cultural story about the song “Enta Omri” by Umm Kulthum. If you’re not interested in this topic, feel free to skip it.</em></p><h3>About the song</h3><p>Umm Kulthum is a name that echoes through the corridors of history. Her most famous song, “Enta Omri” (“You Are My Life”), composed by Mohamed Abdel Wahab, was a significant milestone in her illustrious career.</p><p>The title, ‘Enta Omri,’ is a term of endearment in Arabic, often used to express deep affection. This song, famously dubbed ‘The Meeting of the Clouds,’ marked the first artistic collaboration between Umm Kulthum and Abdel Wahab. With ‘Enta Omri,’ Abdel Wahab blended traditional Egyptian music with innovative Western elements, incorporating the electric guitar and a long instrumental intro. This fusion made the song particularly special, securing its place in Egyptian musical history.</p><p>I chose to share this song because the lyrics of Enta Omri are rich with profound emotional depth. The line, “All I lived before your eyes met mine, was wasted time, how could it still count as mine?” by Ahmed Shafiq Kamel, beautifully captures the transformative power of discovery. It speaks to that moment when something or someone changes your entire perspective, making everything before it feel incomplete.</p><p>Thank you for taking a moment to discover this cultural gem with me. I’d love to hear your thoughts if it resonates with you, too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ykwgNVn1rmzuJvV8uyGtug.png" /></figure><h3>Can Swift code generate Swift code?</h3><p>Is it possible to give Xcode a JSON schema and make it generate a Swift struct? What if the struct is more complex and could have functions inside it? Is that all possible to generate? Do I need to learn some low-level language to do that? Those are all questions I kept asking myself during a previous open-source project. I was working on a Swift project to make it easy for developers to write <a href="https://github.com/sebsto/swift-aws-lambda-runtime/blob/sebsto/deployerplugin_dsl/Sources/AWSLambdaDeploymentDescriptor/DeploymentDescriptor.swift">AWS SAM deployment descriptors</a> in the Swift programming language.</p><p><strong>My main goal?</strong><br>To transform <a href="https://github.com/aws/serverless-application-model/blob/develop/samtranslator/validator/sam_schema/schema.json">JSON Schema</a> to Swift and generate Swift struct based on complex JSON Schema Specifications. The process involved reading a JSON Schema and generating Swift structs that conform to its detailed specifications — I will touch on this later.</p><p>While trying to make this happen, I explored three different Swift code generation techniques:</p><ul><li><strong>Swift Mustache</strong> (a template-based generator)</li><li><strong>Swift Syntax</strong> (a tree-based code generator)</li><li><strong>Swift OpenAPI Generator</strong> (for generating code from OpenAPI specifications)</li></ul><h4>Understanding JSON Schema</h4><p>Before generating code, it’s essential to grasp the concept of <a href="https://json-schema.org/draft-04/schema">JSON Schema.</a></p><p><strong>JSON</strong>, short for <em>JavaScript Object Notation</em>, is a widely used data format, especially in web APIs.<br>J<strong>SON Schema</strong> builds on that by providing a formal way to define the structure and validation rules for JSON data.</p><p>In this section, I implemented the approach using a dedicated Swift package project I created for this article, available on GitHub: <a href="https://github.com/esraaeiid/SwiftCodeGenerator/tree/main/Sources">SwiftCodeGenerator</a></p><p>In <a href="https://github.com/esraaeiid/SwiftCodeGenerator">this project</a>, I used JSON Schema as a blueprint to generate Swift struct.</p><p>Here’s a simplified example of a JSON Schema:</p><pre>{<br>&quot;type&quot;: &quot;object&quot;,<br>&quot;properties&quot;: {<br>&quot;name&quot;: { &quot;type&quot;: &quot;string&quot; },<br>&quot;age&quot;: { &quot;type&quot;: &quot;integer&quot; }<br> }<br>}</pre><p>And here’s the Swift struct that could be generated from it:</p><pre>struct Person: Codable {<br>let name: String<br>let age: Int<br>}</pre><p>This article walks you through each approach of the Swift code generation techniques, highlighting its benefits and challenges. So, keep Umm Kulthum <a href="https://youtu.be/1wBvuZVE7FI?si=pfwIOKUzJcxFLl8f">playing in the background</a>, and let’s dive in! 🎶</p><h3>Approach 1: Swift Mustache</h3><blockquote><a href="https://github.com/hummingbird-project/swift-mustache">Swift Mustache</a> is a logic-less templating engine that uses predefined templates to generate code by replacing placeholders with actual values. It is widely used for generating text-based content, including code, HTML, and configuration files.</blockquote><h4>What is a “Template”?</h4><p>A <strong>template</strong> is a pre-designed format that you can fill in with different content, similar to a <strong>fill-in-the-blanks worksheet</strong>.<br>If you’ve used Shopify to build a website, you may have encountered the term “template” in relation to <strong>Liquid</strong>, a templating language used to generate dynamic web pages.<br><a href="https://shopify.github.io/liquid/">Liquid</a> is an open-source template language created by <a href="https://www.shopify.com/">Shopify</a> and written in Ruby. It powers Shopify themes and allows dynamic content generation for storefronts. After you provide <strong>data</strong>, the templating tool replaces placeholders with real values, producing the final output.</p><p><a href="https://github.com/hummingbird-project/swift-mustache"><em>Swift Mustache</em></a><em> is a logic-less templating engine that uses predefined templates to generate code by replacing placeholders with actual values. It is widely used for generating text-based content, including code, HTML, and configuration files.</em></p><p><strong><em>Templates + Data = Final Output.</em></strong></p><h4>What Does “Logic-less” Mean?</h4><p>A <strong>logic-less</strong> template avoids complex code.<br> Instead of if conditions or loops, Mustache uses simple placeholders and sections to format the output. So, it’s not about “no logic” just minimal logic.</p><h4>How Does Swift Mustache Work?</h4><p>With Swift Mustache, you define a template for a Swift struct, and then use JSON Schema data to populate it.</p><p>Example Mustache Template for a Struct:</p><pre>//This Mustache template generates a Swift struct with Codable conformance <br>// based on a provided name and a list of properties.<br><br>struct {{name}}: Codable {<br>{{#properties}}<br>let {{variable}}: {{type}}<br>{{/properties}}<br>}</pre><p>Generated Swift Code:</p><pre>struct Person: Codable {<br>let name: String<br>let age: Int<br>}</pre><h4>Integrating Swift Mustache in <a href="https://github.com/esraaeiid/SwiftCodeGenerator">Your Project</a></h4><p>Inside the <a href="https://github.com/esraaeiid/SwiftCodeGenerator/tree/main/Sources">SwiftCodeGenerator</a> repository, we’ll create a new package to integrate Swift Mustache. If you’re unfamiliar with Swift packages, check out this <a href="https://developer.apple.com/videos/play/wwdc2018/411/">tutorial</a>.</p><p>In Package.swift, add:</p><pre>// swift-tools-version: 6.0 <br>// The swift-tools-version declares the minimum version of Swift required to build this package. <br><br>// Import the necessary module to describe the package <br>import PackageDescription <br><br>let package = Package( <br>   name: &quot;SwiftGenerator&quot;, <br><br>    // MARK: - Platform Requirements <br>    // Specifies that this package requires macOS 12.0 or later <br>    // This ensures compatibility with the required Swift and dependency versions <br>   platforms: [ <br>        .macOS(.v12) <br>    ], <br><br>    // MARK: - Products <br>    // Defines what this package provides to consumers <br>   products: [ <br>// Library: Can be imported and used by other Swift packages/apps <br>       .library( <br>           name: &quot;SwiftGenerator&quot;,  <br>           targets: [&quot;SwiftGenerator&quot;]),  <br>   ], <br><br>   // MARK: - Dependencies <br>   // External packages this project depends on <br>   dependencies: [ <br> // Hummingbird Mustache: Template engine for generating Swift code <br>       .package(url: &quot;https://github.com/hummingbird-project/hummingbird-mustache.git&quot;, from: &quot;1.0.3&quot;), <br>   ], <br><br>    // MARK: - Targets <br>    // Defines the modules/components of this package <br>   targets: [ <br>// Main library target: Contains the core SwiftGenerator functionality <br>       .target(name: &quot;SwiftGenerator&quot; , dependencies: [ <br>           .product(name: &quot;HummingbirdMustache&quot;, package: &quot;hummingbird-mustache&quot;), <br>       ]), <br>  // Test target: Unit tests for the SwiftGenerator library <br>       .testTarget( <br>           name: &quot;SwiftGeneratorTests&quot;, <br>           dependencies: [&quot;SwiftGenerator&quot;] <br>       ), <br>   ] <br>) </pre><p>2- Create Project Structure:</p><p>Inside your Sources/SwiftGenerator folder:</p><ul><li>StructTemplate.swift → defines the struct template.</li><li>MustacheTemplateGenerator.swift → helper functions for rendering templates.</li><li>main.swift → entry point to generate code.</li></ul><p><strong>The directory structure should look like this:</strong></p><figure><img alt="Xcode project navigator showing the SwiftGenerator package structure. It includes the main ‘SwiftGenerator’ module with a subfolder ‘HummingbirdMustache’ containing two files: MustacheTemplateGenerator and StructTemplate. The ‘SwiftGeneratorExecutable’ module contains a single file named main.swift." src="https://cdn-images-1.medium.com/max/603/1*Op7qGGeFm0CtSem7pCChKA.png" /></figure><p>In StructTemplate.swift, add:</p><pre>extension Templates {<br>    static let structTemplate = &quot;&quot;&quot;<br>struct {{name}}: Codable {<br>    {{#properties}}<br>    let {{variable}}: {{type}}<br>    {{/properties}}<br>}<br>&quot;&quot;&quot;<br>};</pre><p>In MustacheTemplateGenerator.swift, add:</p><pre>import HummingbirdMustache<br>// MARK: - Mustache Template Generator <br>// This enum provides functionality to generate Swift structs using Mustache templates. <br>// It acts as a bridge between the data models and the template rendering system. <br><br>public enum Templates { <br>    static func generateStruct(from data: [String: Any]) -&gt; String { <br>        do { <br>            // Create a Mustache template instance from the struct template string <br>            // This template is defined in SturctTemplate.swift <br><br>            let template = try HBMustacheTemplate(string: Templates.structTemplate) <br>            // Render the template with the provided data <br>            // This replaces all Mustache placeholders with actual values <br>            return template.render(data) <br><br>        } catch { <br>            // Handle template rendering errors gracefully <br>            // Common errors include malformed template syntax or invalid data structure <br>            print(&quot;Error rendering template: \(error)&quot;) <br>            return &quot;&quot; <br>        } <br>    } <br>} </pre><p>In SwiftGenerator.swift adds a dictionary with key-value pairs as an example to generate a struct dynamically:</p><pre>public struct SwiftGenerator { <br>   public init() {} <br>   <br>  //MARK: - Hummingbird Mustache <br>   public func generateWithSwiftMustache() { <br>       let data: [String: Any] = [ <br>           &quot;name&quot;: &quot;User&quot;, <br>           &quot;properties&quot;: [ <br>               [&quot;variable&quot;: &quot;id&quot;, &quot;type&quot;: &quot;Int&quot;], <br>               [&quot;variable&quot;: &quot;name&quot;, &quot;type&quot;: &quot;String&quot;], <br>               [&quot;variable&quot;: &quot;email&quot;, &quot;type&quot;: &quot;String&quot;] <br>           ] <br>       ] <br>// Generate Swift code using the Mustache template <br>       let generatedCode = Templates.generateStruct(from: data) <br>       print(generatedCode) <br>   } <br>} </pre><p>3- Executable Target:</p><p>To execute the package, update Package.swift file to include an executable target:</p><pre>let package = Package( <br>   name: &quot;SwiftGenerator&quot;, <br>   platforms: [ <br>        .macOS(.v12) <br>    ], <br>   products: [ <br><br>// Executable: Command-line tool that can be run directly <br>       .executable( <br>               name: &quot;SwiftGeneratorExecutable&quot;, <br>               targets: [&quot;SwiftGeneratorExecutable&quot;] <br>           ),       <br>      .library( <br>           name: &quot;SwiftGenerator&quot;, <br>           targets: [&quot;SwiftGenerator&quot;]), <br>   ], <br>   dependencies: [ <br>       .package(url: &quot;https://github.com/hummingbird-project/hummingbird-mustache.git&quot;, from: &quot;1.0.3&quot;), <br>   ], <br>   targets: [ <br>       .target(name: &quot;SwiftGenerator&quot; , dependencies: [ <br>           .product(name: &quot;HummingbirdMustache&quot;, package: &quot;hummingbird-mustache&quot;), <br>       ]), <br><br>// Executable target: Command-line interface for the generator <br>       .executableTarget( <br>           name: &quot;SwiftGeneratorExecutable&quot;, <br>           dependencies: [ <br>// Depends on the main SwiftGenerator library <br>               .byName(name: &quot;SwiftGenerator&quot;), <br>           ] <br>       ), <br>       .testTarget( <br>           name: &quot;SwiftGeneratorTests&quot;, <br>           dependencies: [&quot;SwiftGenerator&quot;] <br>       ), <br>   ] <br>) </pre><p>4- Generate the Code:</p><p>In main.swift, call the function <strong>generateWithSwiftMustache</strong> to generate the struct:</p><pre>// MARK: - SwiftGenerator Executable <br>// This is the command-line interface for the SwiftGenerator tool. <br>// It demonstrates how to use the SwiftGenerator library to generate Swift code. <br>import SwiftGenerator <br><br>// MARK: - Initialize Generator <br>// Create an instance of SwiftGenerator to access its code generation capabilities <br>let generator = SwiftGenerator() <br> <br>// Option 1: Generate using Hummingbird Mustache (template-based approach) <br>// This method uses Mustache templates to generate Swift code <br>generator.generateWithSwiftMustache() </pre><p>Then run the project in the terminal using:</p><pre>swift run</pre><p>You should see the generated structure printed on the terminal like this:</p><pre>struct User: Codable {<br>let id: Int<br>let name: String<br>let email: String<br>}</pre><h4>Let’s Spice It Up</h4><p>Want to support optional fields and arrays? Just update the logic in your data model and the Mustache template:</p><p>In SwiftGenerator.swift add the following lines:</p><pre>public func generateWithSwiftMustache() {<br>        let data: [String: Any] = [<br>            &quot;name&quot;: &quot;User&quot;,<br>            &quot;properties&quot;: [<br>                [<br>                    &quot;variable&quot;: &quot;id&quot;,<br>                    &quot;type&quot;: &quot;Int&quot;,<br>                    &quot;isOptional&quot;: false,<br>                    &quot;isArray&quot;: false<br>                ],<br>                [<br>                    &quot;variable&quot;: &quot;name&quot;,<br>                    &quot;type&quot;: &quot;String&quot;,<br>                    &quot;isOptional&quot;: true,<br>                    &quot;isArray&quot;: false<br>                ],<br>                [<br>                    &quot;variable&quot;: &quot;email&quot;,<br>                    &quot;type&quot;: &quot;String&quot;,<br>                    &quot;isOptional&quot;: false,<br>                    &quot;isArray&quot;: true<br>                ]<br>            ]<br>        ]<br>      let generatedCode = Templates.generateStruct(from: data)<br>      print(generatedCode)<br>    }</pre><p>In the<strong> </strong>StructTemplate.swift<strong>, </strong>update the struct template for generating Swift code:</p><pre>extension Templates {<br>    static let structTemplate = &quot;&quot;&quot;<br>struct {{name}}: Codable {<br>    {{#properties}}<br>    let {{variable}}: {{#isArray}}[{{/isArray}}{{type}}{{#isOptional}}?{{/isOptional}}{{#isArray}}]{{/isArray}}<br>    {{/properties}}<br>}<br>&quot;&quot;&quot;<br>}</pre><p><strong>Mustache Syntax Breakdown:</strong></p><p>→ <strong>{{name}}: </strong>Simple variable substitution</p><ul><li>Replaces with the struct name (e.g., “User”, “Person”).</li></ul><p>→ <strong>{{#properties}}: </strong>Section tag (loop)</p><ul><li>Iterates through each property in the properties array.</li><li>Everything between {{#properties}} and {{/properties}} is repeated for each property.</li></ul><p>→ <strong>{{variable}}: </strong>Property name (e.g., “id”, “name”, “email”)</p><p>→ <strong>{{#isArray}}[{{/isArray}}{{type}}{{#isOptional}}?{{/isOptional}}{{#isArray}}]{{/isArray}}: </strong>Complex conditional logic</p><ul><li>{{#isArray}}[{{/isArray}}: If isArray is true, add opening bracket [.</li><li>{{type}}: The Swift type (e.g., “String”, “Int”).</li><li>{{#isOptional}}?{{/isOptional}}: If isOptional is true, add ?.</li><li>{{#isArray}}]{{/isArray}}: If isArray is true, add closing bracket ].</li></ul><p>Then run the project in the terminal using:</p><pre>swift run</pre><p>Voila! You should see the generated structure printed on the terminal like this:</p><pre>struct User: Codable {<br>    let id: Int<br>    let name: String?<br>    let email: [String]<br>}</pre><h4>Writing to a File &amp; Using Structs with Swift Mustache</h4><p>To improve readability and reusability, instead of printing the output directly to the terminal, let’s write the generated code to a file.</p><p><strong>Step 1: Add a File Writing Helper </strong><br>In your SwiftGenerator.swift, add the following function to handle file writing:</p><pre> // MARK: - File Writing Helpers <br>    private func writeToFile(_ content: String, filename: String, directory: String = &quot;Generated&quot;) throws { <br>        let fileManager = FileManager.default <br>        let currentDirectory = fileManager.currentDirectoryPath <br>        let outputDirectory = &quot;\(currentDirectory)/\(directory)&quot; <br><br>        // Create directory if it doesn&#39;t exist <br>        // This ensures the output directory exists before writing files <br>        if !fileManager.fileExists(atPath: outputDirectory) { <br>            try fileManager.createDirectory(atPath: outputDirectory, withIntermediateDirectories: true) <br>        } <br><br>        // Write the generated code to the file <br>        let filePath = &quot;\(outputDirectory)/\(filename)&quot; <br>        try content.write(toFile: filePath, atomically: true, encoding: .utf8) <br>        print(&quot; Generated file: \(filePath)&quot;) <br>    } </pre><p><strong>Step 2: Add Struct and Property Models<br></strong>Create a new Model folder inside Sources/SwiftGenerator, and add two files, StructData.swift and Property.swift.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*bJqFtvu7PJWVP9Ikvb5tmg.png" /></figure><ul><li>In the<strong> </strong>StructData.swift:</li></ul><pre>import Foundation  <br><br>public struct StructData { <br>    let name: String <br>    let properties: [Property] <br><br>    public init(name: String, properties: [Property]) { <br>        self.name = name <br>        self.properties = properties <br>    } <br>     <br>    // Convert to dictionary for Mustache template <br>    func toDictionary() -&gt; [String: Any] { <br>        return [ <br>            &quot;name&quot;: name, <br>            &quot;properties&quot;: properties.map { property in <br>                [ <br>                    &quot;variable&quot;: property.variable, <br>                    &quot;type&quot;: property.type, <br>                    &quot;isOptional&quot;: property.isOptional, <br>                    &quot;isArray&quot;: property.isArray <br>                ] <br>            } <br>        ] <br>    } <br>} <br><br>// MARK: - Convenience Initializers <br>extension StructData { <br>    public static func user() -&gt; StructData { <br>        return StructData( <br>            name: &quot;User&quot;, <br>            properties: [ <br>                Property(variable: &quot;id&quot;, type: &quot;Int&quot;), <br>                Property.optional(&quot;name&quot;, type: &quot;String&quot;), <br>                Property.array(&quot;emails&quot;, type: &quot;String&quot;) <br>            ] <br>        ) <br>    } <br><br>    public static func person() -&gt; StructData { <br>        return StructData( <br>            name: &quot;Person&quot;, <br>            properties: [ <br>                Property(variable: &quot;id&quot;, type: &quot;UUID&quot;), <br>                Property.optional(&quot;firstName&quot;, type: &quot;String&quot;), <br>                Property.optional(&quot;lastName&quot;, type: &quot;String&quot;), <br>                Property.array(&quot;phoneNumbers&quot;, type: &quot;String&quot;), <br>                Property(variable: &quot;age&quot;, type: &quot;Int&quot;) <br>            ] <br>        ) <br>    } <br>}</pre><p>In the<strong> </strong>Property.swift:</p><pre>import Foundation <br><br>public struct Property { <br>    let variable: String <br>    let type: String <br>    let isOptional: Bool <br>    let isArray: Bool <br><br>    public init(variable: String, type: String, isOptional: Bool = false, isArray: Bool = false) { <br>        self.variable = variable <br>        self.type = type <br>        self.isOptional = isOptional <br>        self.isArray = isArray <br>    } <br>} <br><br>// MARK: - Convenience Initializers <br>extension Property { <br>    public static func optional(_ variable: String, type: String) -&gt; Property { <br>        return Property(variable: variable, type: type, isOptional: true) <br>    } <br><br>    public static func array(_ variable: String, type: String) -&gt; Property { <br>        return Property(variable: variable, type: type, isArray: true) <br>    } <br><br>    public static func optionalArray(_ variable: String, type: String) -&gt; Property { <br>        return Property(variable: variable, type: type, isOptional: true, isArray: true) <br>    } <br>} </pre><p><strong>Step 3: Update the </strong>generateWithSwiftMustache()<strong>function<br></strong>Now update your generation function to use StructData and write the result to a file:</p><pre>  //MARK: - Hummingbird Mustache <br>    public func generateWithSwiftMustache() { <br>        let structData = StructData.user() <br><br>        // Generate Swift code using the Mustache template <br>        let generatedCode = Templates.generateStruct(from: structData.toDictionary()) <br><br>        // Write the generated code to a file <br>        do { <br>            try writeToFile(generatedCode, filename: &quot;User.swift&quot;) <br>        } catch { <br>            print(&quot;Error writing file: \(error)&quot;) <br>        } <br>    } </pre><p><strong>Final Hierarchy &amp; Output <br></strong>After running the command:</p><pre>swift run</pre><p>You can see a new Generated directory with a User.swift file inside:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*0mcakuDp7L-eQXswHpaQjQ.png" /></figure><h4>Other Use Cases for Swift Mustache</h4><p><strong><em>HTML Rendering</em></strong></p><p>Swift Mustache can generate <strong>dynamic HTML</strong> for server-side Swift frameworks like <strong>Vapor</strong>.</p><p>For example, if you’re building a <strong>blog</strong>, you don’t want to write a new HTML page whenever you create a new post. Instead, you can use a <strong>template</strong> that automatically fills in the title, author, and content.</p><p><a href="https://vapor.codes/">Vapor</a> is a <strong>server-side Swift framework</strong> for building web applications and APIs. Unlike iOS apps on a user’s device, <strong>server-side Swift runs on a web server</strong> and responds with HTML pages or JSON data.</p><h4>Is Swift Mustache Limited to Swift?</h4><p>Yes, Swift Mustache is a Swift-specific implementation of the <a href="https://mustache.github.io/">Mustache templating language</a>. However, Mustache itself is not limited to Swift , it has implementations in multiple languages, including:</p><ul><li><strong>JavaScript</strong></li><li><strong>Python</strong></li><li><strong>Ruby</strong></li><li><strong>Java</strong></li><li><strong>PHP</strong></li></ul><h4>Benefits of Swift Mustache</h4><ul><li>Customizable templates with a separation of code generation templates from the core code, along with <a href="https://mustache.github.io/mustache.5.html">examples</a> for multiple cases.</li><li>Supports custom inheritance, loops, optionals, and encoding/decoding.</li></ul><h4>Challenges of using Swift Mustache</h4><ul><li>Mustache templates lack detailed debugging information, making it difficult to identify missing elements or required fixes.</li><li>No comprehensive documentation was found that showcases various template examples.</li><li>Mustache is a templating language that requires a learning curve for generating complex code, such as manual decoding and encoding, methods, statements, and enum with associated values.</li></ul><p>For more details, check out the <a href="https://github.com/hummingbird-project/swift-mustache/tree/main/documentation">Mustache Syntax Documentation</a>.</p><h3><strong>Conclusion (to Part 1!)</strong></h3><p>In this part, we laid the groundwork for code generation in Swift using Swift Mustache, which offers flexibility and simplicity for basic struct generation.<br>But what if you need more structure, type safety, and integration with the Swift compiler?</p><p>In <a href="https://medium.com/deloitte-uk-cloud-blog/a-guide-to-generating-swift-code-with-swift-syntax-and-swift-openapi-part-2-c277388ad38c"><strong>Part Two</strong></a>, we’ll dive deeper into <strong>SwiftSyntax</strong> and <strong>Swift OpenAPI Generator, </strong>exploring how these tools give you precise control over how your Swift code is constructed from schemas and specifications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d985711e2c2c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/deloitte-uk-cloud-blog/a-guide-to-generating-swift-code-with-swift-mustache-part-1-d985711e2c2c">A Guide to Generating Swift Code with Swift Mustache (Part 1)</a> was originally published in <a href="https://medium.com/deloitte-uk-cloud-blog">Deloitte UK Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>