What are Swift macros?
Why Interviewers Ask This
Senior Swift & iOS engineers are expected to reason about architecture, performance, and edge cases. This question separates mid-level from senior candidates by testing deep system-level understanding.
Answer
Swift Macros (Swift 5.9) are compile-time code generation mechanisms — they expand to produce additional Swift code at compile time, eliminating boilerplate. Unlike C preprocessor macros, Swift macros are type-safe, produce well-formed code, and are debuggable. Macro types: (1) Expression macros (#stringify): transform expressions: let (value, string) = #stringify(42 + 2) // value=44, string="42 + 2" (2) Freestanding macros (#warning, #error, #URL): let url = #URL("https://api.example.com") // Validated at compile time!; (3) Attached macros (@Observable, @Model): enhance declarations. @Observable (Swift 5.9, replacement for ObservableObject): import Observation @Observable class ViewModel { var name = "" // Automatically generates @Published-like behavior var count = 0 // Observation tracking without @Published func increment() { count += 1 } } // In SwiftUI: struct View: View { @State private var vm = ViewModel() // No @StateObject needed! var body: some View { Text(vm.name) } }. SwiftData @Model macro: import SwiftData @Model class User { var name: String var email: String @Relationship(deleteRule: .cascade) var posts: [Post] init(name: String, email: String) { self.name = name; self.email = email } }. Custom macros: implement as a Swift package that conforms to specific macro protocols. Debug with expanded macro view in Xcode. Built-in macros: @discardableResult (suppress warning), @warn_unhandled_result, #file, #line, #function, #column.
Pro Tip
Back up your answer with a specific project or situation. Saying 'In my last Swift & iOS project, I used this when...' immediately makes your answer more credible and memorable.