DevPrep

All topics › Modern Swift

What are macros (Swift 5.9+)?

Senior PRO

The idea

Macros are compile-time metaprogramming: the compiler hands the syntax of the annotated code to a plugin (a separate SwiftSyntax-based process), the plugin returns new code, and the result is compiled as ordinary Swift. A macro can only add code, never modify or remove existing code, and runs in a sandbox with no file or network access.

An important caveat: the macro implementation sees only the AST without type information. So "type safety" means the expansion result is checked by the compiler like regular code (unlike reflection or text-based codegen), not that the macro knows the types. The expansion can be inspected in Xcode (Expand Macro).

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store