Swift
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Optionals
-
Section 4: Object-Oriented and Value Types
-
Section 5: Memory Management
-
Section 6: Generics and Error Handling
-
Section 7: Concurrency
-
Section 8: Working with Collections
-
Section 9: Codable and Data Handling
-
Section 10: Protocol-Oriented Programming
-
Section 11: Testing and Tooling
-
Section 12: Practical Projects
-
Section 13: Interview Practice
-
Section 14: More Practice Exercises
-
Section 15: More Standard Library
-
Section 16: Advanced Concurrency
-
Section 17: Foundation Framework Deep Dive
-
Section 18: URLSession and Networking Deep Dive
-
Section 19: Combine Framework
-
Section 20: SwiftUI Fundamentals for Swift Developers
-
Section 21: Server-Side Swift with Vapor
-
Section 22: Swift Package Manager Deep Dive
-
Section 23: Swift Concurrency Deep Dive
-
Section 24: More Language Features
-
Section 25: Error Handling Deep Dive
-
Section 26: Testing Deep Dive
-
Section 27: Data Structures and Algorithms in Swift
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Swift Macros (Swift 5.9+)
-
Section 31: Property Wrappers Ecosystem
-
Section 32: Swift Interop Deep Dive
-
Section 33: iOS App Architecture Patterns
-
Section 34: Performance and Debugging
-
Section 35: App Distribution and CI/CD
-
Section 36: More Practical Projects
-
Section 37: SwiftData and Persistence
-
Section 38: More Design Patterns
-
Section 39: More Review and Practice
-
Section 40: More Foundation Deep Dive
-
Section 41: Advanced Collections in Swift
-
Section 42: Advanced Generics Practice
-
Section 43: UIKit for Legacy and Hybrid Apps
-
Section 44: watchOS and visionOS Development Basics
-
Section 45: More Networking Patterns
-
Section 46: More Testing Practice
-
Section 47: Accessibility in Swift Apps
-
Section 48: Localization
-
Section 49: More Practical Projects Round 2
-
Section 50: Swift Charts Framework
-
Section 51: More Interview and Algorithm Practice
-
Section 52: Final Practice and Mastery
-
Section 53: Swift Compiler and Build System
-
Section 54: More Concurrency Practice
-
Section 55: App Store Guidelines and Review
-
Section 56: More Design and Architecture
135: Writing a Freestanding Macro
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
Regexobject 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.
There are no comments for now.