Skip to Content
Course content

135: Writing a Freestanding Macro

Click on the "Edit" button in the top corner of the screen to edit your slide content.

By now, you've likely seen attached macros that add members to a class or add modifiers to a property. Those are great, but freestanding macros are a different beast entirely. They don't "attach" to anything; they live on their own, usually starting with a hash symbol like #myMacro(args). They take an expression and transform it into another expression. I like to think of them as "compile-time functions" that can fundamentally rewrite your code before the compiler even starts turning it into machine instructions.

The Shortcut That Doesn't Actually Save You

Let's say we want a macro that makes creating URL objects less tedious. In Swift, URL(string: "...") is an optional, which means we're constantly force-unwrapping them or using if let blocks for URLs we know are correct because we hard-coded them. A naive approach to a freestanding macro would be to simply wrap the input string in a force-unwrap.

// The "Lazy" implementation
public struct URLMacro: ExpressionMacro {
    public static func expansion(
        of node: some FreestandingMacroExpansionSyntax,
        in context: some MacroExpansionContext
    ) -> ExprSyntax {
        // Just take the first argument and wrap it
        guard let argument = node.argumentList.first?.expression else {
            fatalError("URL macro requires an argument")
        }
        return "URL(string: \(argument))!"
    }
}

I've seen this approach a lot when developers first touch macros. It looks clean in the call site—let api = #url("https://api.example.com")—but it's honestly a waste of a macro. All we've done here is create a fancy alias for a force-unwrap. If you make a typo in that string, the app still crashes at runtime. We've moved the syntax around, but we haven't actually improved the safety of the system. If this is all you're doing, you might as well just write a helper function.

Moving the Failure to Compile Time

The real power of a freestanding macro is that it has access to the SwiftSyntax tree. Instead of just blindly wrapping the input, we can actually inspect the value being passed in. If we can validate the URL during the expansion phase, we can stop the build entirely if the URL is malformed. This turns a potential production crash into a compiler error.

To do this, we need to ensure the argument is actually a string literal and then validate its contents. If it's not valid, we don't just return a broken expression; we emit a diagnostic.

public struct URLMacro: ExpressionMacro {
    public static func expansion(
        of node: some FreestandingMacroExpansionSyntax,
        in context: some MacroExpansionContext
    ) -> ExprSyntax {
        guard let argument = node.argumentList.first?.expression,
              let stringLiteral = argument.as(StringLiteralExprSyntax.self),
              let value = stringLiteral.representedValue else {
            // We can't even find a string literal here
            return "URL(string: \"invalid\")!" 
        }

        // Validate the URL at compile time
        if URL(string: value) == nil {
            // This is the magic part: telling the compiler to show an error
            // in the IDE at the exact location of the macro call.
            // (Note: Simplified for brevity; actual diagnostics use context.emit)
            return "fatalError(\"Invalid URL: \(value)\")"
        }

        return "URL(string: \(argument))!"
    }
}

Now, the trade-off shifts. In the first version, the macro was trivial to write but provided zero safety. In this version, we're doing a bit more heavy lifting with SwiftSyntax types (like StringLiteralExprSyntax), but we've fundamentally changed the developer experience. You no longer have to run the app to find out you missed a colon in your URL string; the IDE tells you immediately.

The Tax of Using SwiftSyntax

I want to be honest with you: writing macros this way is a bit "noisy." You're no longer writing Swift logic; you're writing logic about Swift code. You have to deal with Syntax protocols, optional casting, and the specific way SwiftSyntax represents literals. It feels clunky because you're essentially writing a mini-compiler.

But that's the price of admission. When you move a check from runtime to compile-time, you reduce the surface area for bugs. The rule of thumb I use is this: if your macro is just a shortcut for a function call, don't make it a macro. If your macro can use the structure of the code to prevent a runtime failure, it's exactly the right tool for the job.




📋 Practical Task

Build a Compile-Time Regex Validator Macro

Create a freestanding macro called #regex. Instead of simply wrapping a string in try Regex(stringLiteral: ...) and risking a runtime crash if the pattern is invalid, your macro should:

  • Extract the string literal passed as the first argument.
  • Attempt to initialize a Regex object with that string during the expansion phase.
  • If the regex pattern is invalid, return a fatalError("Invalid Regex pattern") expression (or use the context to emit a diagnostic) so the developer knows exactly which pattern is broken before the code ever runs.
  • If valid, return the standard try! Regex("\(argument)") expression.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.