/Swift-Macros

A curated list of awesome Swift Macros

MIT LicenseMIT

Swift Macros 🚀



Swift Macros have brought in a new wave of possibilities. The aim of this project is to curate a list of community-created Macros and associated learning resources.

A lot of use-cases my Sourcery covered before can now be implemented by Swift Macros.






Learning Resources 📚

Tools

Apple:

Dive into Swift Macros with these WWDC sessions:

  • Write Swift Macros: An introductory session on Macros, their roles, and workings with a basic example.
  • Expand Swift Macros: A deeper exploration into crafting your Macros and testing their functionality.

Other Apple Resources:

  • Macros: The Official Step-by-Step Guide to Using Macros for Compile-Time Code Generation in Swift.
  • Example Swift Macros: Check out real-world examples from Apple, like @AddCompletionHandler and @AddAsync.

Community Blogs


Macros 💻

SwiftUI

Models

  • Coding Keys: Effortlessly generate CodingKeys for converting snake_case to lowerCamelCase.
  • Builder pattern: Apply the Builder Pattern with ease by generating a Builder helper class, mimicking stored properties of the associated struct.
  • EnhancedMirror: An experimental Mirror alternative that utilizes Swift Macros for static reflection.

Testing

  • Power Assert: Adds assertions that can automatically produce information about the values being evaluated, and present it in an easily digestible form.
  • Spyable: A Swift macro that simplifies and automates the process of creating spies for testing. Using the @Spyable annotation on a protocol, the macro generates a spy class that implements the same interface as the protocol and keeps track of interactions with its methods and properties.

Networking

  • SwiftRequest: SwiftRequest is a lightweight, type-safe HTTP client for Swift, streamlining the construction and execution of HTTP request build on top of Macros.

Enums

  • ExtractCaseValue: A Swift macro that extracts associated values from enum cases.

Misc

  • MacroKit: A collection of macros including:
    • @PublicInit: Generate public memberwise init
    • @GenerateMock: Create a mock object for testing from a protocol
    • @KeyPathIterable: Like CaseIterable but for available keypaths on a type
    • @StaticMemberIterable: Like CaseIterable but for available static members on a type
    • More to come...
  • InitMacro: A Swift Macro implementation that generates initializers for classes and structs with support for default values, wildcards and access control.
  • AssociatedObject: A Swift Macro for adding stored properties in Extension to classes defined in external modules, etc.
    (This is implemented by wrapping objc_getAssociatedObject/objc_setAssociatedObject.)

Take part in this exciting evolution in Swift. Your contributions are most welcome!