A Guide to Generating Swift Code with Swift Syntax and Swift OpenAPI (Part 2)
Article Summary
Esraa Eid from Deloitte UK tackles Swift code generation with a deep dive into SwiftSyntax and OpenAPI. If you've ever struggled with generating type-safe models from specs, this comparison will change how you approach automation.
This is Part 2 of a comprehensive guide exploring three approaches to Swift code generation: Mustache templates, SwiftSyntax, and Swift OpenAPI Generator. Eid provides hands-on implementation examples with a working GitHub repository, comparing precision, flexibility, and real-world tradeoffs for each tool.
Key Takeaways
- SwiftSyntax offers compiler-friendly precision through Abstract Syntax Trees (ASTs)
- OpenAPI Generator automates API client code but sacrifices formatting control
- Custom property models enable optional types, arrays, and batch struct generation
- SwiftSyntax requires more setup but delivers type-safe, maintainable code
- Mustache works for quick templates; SwiftSyntax wins for production complexity
SwiftSyntax emerges as the most suitable tool for generating precise, compiler-compatible Swift code from JSON Schema, despite its steeper learning curve compared to template-based alternatives.
About This Article
Developers have a hard time generating Swift structs that handle optional types, arrays, and complex nested properties without breaking compiler compatibility or messing up code formatting.
Esraa Eid built the SwiftSyntaxProperty model with convenience initializers for optional and array types. It uses SwiftSyntaxBuilder to construct syntax trees programmatically and handles trivia properly so the formatting stays clean.
This approach lets you generate multiple structs like Person and Product in batches and automatically write them to a Generated directory. It cuts down on manual boilerplate code while keeping type safety and AST precision intact.