skip to content

Metaprogramming Features

Property wrappers, result builders, macros and key paths: the features SwiftUI and SwiftData are built on. Interviewers ask how they work underneath the frameworks' syntax.

on this pageshow

explore

questions

21

In Swift, how does contacts.map(\.name) work, and why does passing a stored KeyPath variable to map fail?

level: juniorimportance: must knowfreq 60%

answer

  1. a literal standing in for a closure
  2. (Root) -> Value from \Root.value
  3. literal only, not a variable
  4. subscript keyPath: inside a closure

basics

~20 s

A key-path literal such as .name converts to a (Contact) -> String function wherever one is expected, so map applies it to each element. Only the literal converts; a stored KeyPath value needs a closure: { $0[keyPath: path] }.

solid answer

~30 s

A key-path expression like `\Contact.name` is normally a `KeyPath` object, but when the context expects a function `(Root) -> Value`, the compiler converts the **literal** into a closure equivalent to `{ $0[keyPath: \Contact.name] }`. That is why `map(\.name)`, `filter(\.isFavorite)`, `compactMap(\.email)` and `contains(where: \.isFavorite)` all work, and why `compactMap(\.self)` unwraps an array of optionals. The conversion applies only to the literal syntax: a constant `let path = \Contact.name` already has the type `WritableKeyPath<Contact, String>`, which is a class, not a function, so `map(path)` fails with `no exact matches in call to instance method 'map'`. Write `map { $0[keyPath: path] }` instead.

code

swift · 23 lines
swift
struct Contact {
    var name: String
    var email: String?
    var isFavorite: Bool
}

let contacts = [
    Contact(name: "Ana", email: "[email protected]", isFavorite: true),
    Contact(name: "Bo", email: nil, isFavorite: false),
]

let names = contacts.map(\.name)                  // ["Ana", "Bo"]
let favorites = contacts.filter(\.isFavorite)     // [Ana]
let emails = contacts.compactMap(\.email)         // ["[email protected]"]
let ids = [3, nil, 7].compactMap(\.self)          // [3, 7]

let nameOf: (Contact) -> String = \.name          // a key-path literal converts to a function
print(names, favorites.count, emails, ids, nameOf(contacts[1]))

let path = \Contact.name                          // a stored KeyPath value, not a literal
// contacts.map(path)                             // error: no exact matches in call to instance method 'map'
let viaSubscript = contacts.map { $0[keyPath: path] }
print(viaSubscript)

go deeper

for a junior

Recall that map(.name) means map { $0.name }, that filter needs a Bool path, and that compactMap(.self) drops nils.

for a middle

Explain that the compiler converts a key-path literal into a (Root) -> Value closure, and that a stored key path is a class instance applied with the keyPath subscript.

for a senior

Show where the literal and a closure diverge: subscript arguments captured at creation, and APIs that should take a function type so callers can pass either.

for a principal

Frame the trade-off as readability: key-path literals shorten pipelines, but code that stores and passes key paths around needs explicit keyPath subscripts and clear parameter types.

## What a key-path expression is A **key-path expression** names a property or subscript of a type without naming an instance: `\Contact.name` means "the `name` of some `Contact`". At compile time it becomes an instance of one of the standard library's key-path classes, here `WritableKeyPath<Contact, String>`, and you apply it to a value with the built-in subscript `value[keyPath: path]`. The root type may be omitted when the context supplies it, so `\.name` is the same expression wherever the compiler already knows the root is `Contact`. ## The key-path-as-function conversion Swift also lets a key-path **literal** appear where a function is expected. A literal whose root is `Root` and whose path produces `Value` is accepted in place of a closure of type `(Root) -> Value`, and the compiler generates a closure equivalent to `{ $0[keyPath: \Root.value] }`. Everyday uses: - `contacts.map(\.name)` returns `[String]`, the same as `contacts.map { $0.name }`. - `contacts.filter(\.isFavorite)` works because the path produces a `Bool`, which is what `filter` needs. - `contacts.compactMap(\.email)` drops the contacts whose `email` is `nil`. - `contacts.contains(where: \.isFavorite)`, `first(where:)` and `allSatisfy(_:)` accept the same `Bool` paths. - `let nameOf: (Contact) -> String = \.name` stores the converted function in a constant of function type. The rule is about **types**, not about particular methods: any parameter of function type `(Root) -> Value` can take the literal, including your own functions. The value type must match what the function returns; `filter(\.name)` fails because `String` is not `Bool`. ## The identity key path, \.self `\.self` is the **identity key path**: its path is the whole value, so `\Contact.self` is a `WritableKeyPath<Contact, Contact>`. Converted to a function it is the identity function, which makes a few idioms read well: 1. `[3, nil, 7].compactMap(\.self)` returns `[3, 7]`, because the identity of an `Int?` is that optional, and `compactMap` drops the `nil`. 2. `[true, false].filter(\.self)` keeps the `true` elements. 3. `value[keyPath: \.self] = newValue` replaces a whole variable in one step. ## Why a stored KeyPath does not convert The conversion is defined for the **literal syntax only**. The type checker prefers a key-path type for `\Contact.name` but also allows a function type when the context demands one; once the literal has been bound to a constant, that choice is over. `let path = \Contact.name` has the class type `WritableKeyPath<Contact, String>`, and a class instance is not a function, so: ```swift struct Contact { var name: String } let contacts = [Contact(name: "Ana"), Contact(name: "Bo")] let path = \Contact.name // contacts.map(path) // error: no exact matches in call to instance method 'map' let names = contacts.map { $0[keyPath: path] } ``` A coercion does not help either: `path as (Contact) -> String` fails with `cannot convert value of type 'WritableKeyPath<Contact, String>' to type '(Contact) -> String' in coercion`. Code that receives key paths at run time, such as a column list or a configurable mapping, applies them with `[keyPath:]` inside a closure, or declares its own helper that takes a `KeyPath<Element, T>` parameter and does the same. | Form | Accepted where `(Contact) -> String` is expected? | |---|---| | `\.name` or `\Contact.name` written in place | yes, converted to a closure | | `{ $0.name }` | yes, an ordinary closure | | `let path = \Contact.name`, then `path` | no, it is a `WritableKeyPath` object | | `{ $0[keyPath: path] }` | yes, a closure applying the stored path | ## When the expression is evaluated A key-path expression is evaluated **once**, where it is written. If a subscript component contains a variable or a function call, its value is captured at that moment with value semantics: after `var i = 0; let path = \[String].[i]`, changing `i` to `1` does not move `path`, which still reads element `0`. A closure that reads `i` sees the new value. This is where the literal and a hand-written closure can behave differently, so a subscript index computed from mutable state belongs in a closure when it must follow that state. ## What to remember - The conversion turns a literal into a closure; the closure reads the property through the key path. - `\.self` is the identity path, handy with `compactMap` and `filter`. - A key path held in a variable is an object of a key-path class; apply it with `[keyPath:]`.

  • Why does contacts.filter(\.name) fail to compile when contacts.filter(\.isFavorite) works?
    The literal converts to `(Contact) -> Value`, where `Value` is whatever the path produces. `filter` needs `(Contact) -> Bool`, so only a path ending in a `Bool` fits; `\.name` produces a `String`. Write the test as a closure, such as `filter { !$0.name.isEmpty }`.
  • How do you let your own function accept either a key-path literal or a closure?
    Declare the parameter as a function type, for example `func column<T>(_ value: (Contact) -> T)`. Callers can then pass `\.name` or `{ $0.name.uppercased() }`. If you declare it as `KeyPath<Contact, T>` instead, callers must pass a key path, and a closure no longer fits.
  • Why does var i = 0; let path = \[String].[i] keep reading index 0 after i changes?
    The subscript argument is evaluated once, when the key-path expression is evaluated, and stored in the key path by value. Later changes to `i` do not reach it. A closure `{ $0[i] }` captures the variable instead, so it reads the current value.

A key path is like a column heading in a spreadsheet: "Name" means nothing until you point it at a row, and the same heading works on every row. Handing map the heading means "read this column from each row"; a heading you saved on a sticky note still has to be read out by someone, which is the closure.

  • A stored KeyPath constant can be passed anywhere a closure is expected.
  • filter(\.name) works because any property can act as a predicate.
  • \.self is a special case only allowed in SwiftUI's ForEach.
  • A key path re-evaluates its subscript arguments every time it is applied.
  • map has a dedicated KeyPath overload in the standard library.
open as a page

In Swift, what must a @propertyWrapper type declare, and what does the compiler generate when you write @Trimmed var email: String?

level: juniorimportance: must knowfreq 72%

basics

~20 s

A @propertyWrapper type must declare a non-static wrappedValue property. For @Trimmed var email, Swift synthesizes private storage _email of type Trimmed and turns email into a computed property that forwards get and set to _email.wrappedValue.

open as a page

In a Swift property wrapper, what is projectedValue, and how do $volume and _volume differ from volume?

level: middleimportance: must knowfreq 62%

basics

~10 s

projectedValue is an optional property a wrapper declares to expose extra information; Swift surfaces it as $volume with volume's access level. volume forwards to wrappedValue, and _volume is the private wrapper instance itself.

open as a page

In Swift, what does the @resultBuilder attribute do, and how does a closure of separate expression lines become one value?

level: juniorimportance: should knowfreq 35%

basics

~20 s

@resultBuilder marks a type whose static build methods the compiler calls. Where that type is written as an attribute, the compiler rewrites the body: each expression line becomes a partial result, and buildBlock (or buildPartialBlock) combines them into the return value.

open as a page

In Swift, what happens at compile time when code calls a freestanding macro such as `#checkedURL("https://example.com")`, and how does that differ from a function call?

level: juniorimportance: should knowfreq 40%

basics

~20 s

The compiler expands it during the build: the macro's implementation receives the call's syntax and returns code that replaces the call, which is then type-checked. A function runs later with real values; a macro's thrown error fails the build.

open as a page

Why does a Swift result-builder closure reject guard, break and defer, and what does an explicit return do to it?

level: middleimportance: should knowfreq 28%

basics

~20 s

A builder transform needs every statement to map onto partial results in a fixed structure, so guard, break, continue, defer, while and do-catch are rejected. An explicit return turns the transform off, and the body type-checks as ordinary code.

open as a page

In a Swift result builder, what do buildExpression(_:) and buildFinalResult(_:) let an email DSL accept and return?

level: middleimportance: should knowfreq 18%

basics

~10 s

buildExpression(:) lifts each expression line into the builder's component type, so overloads can accept both String and Link lines. buildFinalResult(:) converts the outermost component into the returned type, such as a rendered String.

open as a page

In a Swift result builder, which build methods let the closure use an if without else and a for-in loop, and what does each receive?

level: middleimportance: should knowfreq 30%

basics

~10 s

buildOptional(:) enables an if without else and receives the branch's block result, or nil when the condition is false. buildArray(:) enables for-in and receives an array holding one block result per iteration.

open as a page

In Swift, how do optional chaining, force unwrapping and subscripts inside a key path change its type, and what does appending(path:) return?

level: middleimportance: should knowfreq 25%

basics

~20 s

Optional chaining makes a key path read-only with an Optional value; force unwrapping keeps it writable but traps on nil; subscripts need Hashable arguments. Typed appending(path:) returns a typed path; on PartialKeyPath or AnyKeyPath it returns an Optional.

open as a page

In Swift, what decides whether a key-path expression is a KeyPath, WritableKeyPath or ReferenceWritableKeyPath, and why does a generic settings row care?

level: middleimportance: should knowfreq 40%

basics

~20 s

The path decides: any read-only step gives KeyPath, settable steps through values give WritableKeyPath, and a settable member behind a class reference gives ReferenceWritableKeyPath. A settings row that writes must demand WritableKeyPath, so read-only properties fail to compile.

open as a page

In Swift, how do freestanding `#` macros differ from attached `@` macros, and which roles can each kind declare?

level: middleimportance: should knowfreq 30%

basics

~20 s

A freestanding macro is called with # on its own and has one role, expression or declaration. An attached macro is written as @Name on a declaration and adds code through peer, member, memberAttribute, accessor, extension or body roles.

open as a page

In Swift, which declarations besides stored properties can carry a property wrapper attribute, and which ones does the compiler reject?

level: middleimportance: should knowfreq 38%

basics

~20 s

Besides stored var properties, wrappers work on static vars, local variables (Swift 5.4) and function and closure parameters (Swift 5.5). The compiler rejects them on let, computed, global, lazy, weak and overriding properties, and protocol or extension instance properties.

open as a page

In a Swift result builder, how do if/else and switch become nested buildEither calls, and when is buildLimitedAvailability needed?

level: seniorimportance: should knowfreq 22%

basics

~20 s

The compiler puts each branch at a leaf of a binary tree and wraps its result in buildEither(first:) or buildEither(second:) along the path. buildLimitedAvailability erases an if #available branch's type so it does not leak into the result type.

open as a page

In Swift, how does @dynamicMemberLookup with a String subscript differ from one taking a KeyPath, and what can go wrong with each?

level: seniorimportance: should knowfreq 30%

basics

~20 s

@dynamicMemberLookup turns x.name, when no member called name exists, into x[dynamicMember:]. A String subscript accepts any name, so typos compile; a KeyPath subscript accepts only real members of a root type, typed and checked at compile time.

open as a page

In Swift, why does stacking @Trimmed @Lowercased on a String property fail to compile, and how do stacked property wrappers nest?

level: seniorimportance: should knowfreq 28%

basics

~10 s

Stacked wrappers nest, with the first attribute outermost, so @Trimmed @Lowercased needs Trimmed's wrappedValue to hold a Lowercased; Trimmed's is a String, so it fails. A generic outer wrapper, such as Counted<Value>, composes fine.

open as a page

A Swift AudioSettings struct changes @Clamped(0...100) var volume = 50 to @Clamped(wrappedValue: 50, 0...100) var volume: Int; why does AudioSettings(volume: 70) stop compiling?

level: seniorimportance: should knowfreq 30%

basics

~20 s

The memberwise parameter takes Int only when volume has an = initial value, or no value and no attribute arguments; spelling wrappedValue: inside the attribute makes the parameter Clamped, so passing 70 no longer type-checks.

open as a page

As the lead of a Swift codebase, how do you decide whether to adopt a third-party macro package, write your own macros, or avoid macros for a given problem?

level: principalimportance: should knowfreq 15%

basics

~20 s

Treat a macro as a build-time dependency: weigh clean-build cost, swift-syntax version coupling, trust in a plug-in that runs during builds and writes into your binary, and whether the expansion is readable and tested. Prefer plain language features when they suffice.

open as a page

In Swift, what must a @dynamicCallable type implement, and how does the compiler choose between its two dynamicallyCall methods?

level: middleimportance: nice to knowfreq 10%

basics

~10 s

A @dynamicCallable type implements dynamicallyCall(withArguments:), taking an ExpressibleByArrayLiteral parameter, or dynamicallyCall(withKeywordArguments:), taking an ExpressibleByDictionaryLiteral one with string-literal keys, or both. A call with any argument label uses the keyword method.

open as a page

In Swift, how is a macro declared with `#externalMacro(module:type:)` and implemented with SwiftSyntax, and where does its implementation actually run?

level: middleimportance: nice to knowfreq 22%

basics

~20 s

A macro declaration gives the name, signature and role, and #externalMacro(module:type:) points at a type in a separate macro target. That type conforms to a SwiftSyntax protocol such as ExpressionMacro, and the compiler runs it as a plug-in while building callers.

open as a page

Why did Swift 5.7 add buildPartialBlock(first:) and buildPartialBlock(accumulated:next:) to result builders, and when does the compiler call them?

level: seniorimportance: nice to knowfreq 8%

basics

~20 s

buildPartialBlock folds a block one statement at a time, so a typed builder handles any number of differently typed lines without one buildBlock overload per arity. When both methods exist and are available at the call site, the compiler prefers them.

open as a page

A Swift peer macro `@AddCompletionHandler` fails with "declaration name 'fetchAvatarWithCompletion' is not covered by macro"; why, and why can it not rewrite the async method itself instead?

level: seniorimportance: nice to knowfreq 18%

basics

~20 s

Its declaration says names: overloaded, which covers only declarations named fetchAvatar, so fetchAvatarWithCompletion is rejected. Emit an overload of fetchAvatar or declare suffixed(WithCompletion). A peer macro only adds declarations beside the method; it cannot change it.

open as a page