In Swift, how does @dynamicMemberLookup with a String subscript differ from one taking a KeyPath, and what can go wrong with each?
answer
- dot syntax rewritten to a subscript
- subscript(dynamicMember:) is required
- declared members are found first
- string names vs typed key paths
- typos: run time vs compile time
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.
solid answer
~40 s`@dynamicMemberLookup` requires a `subscript(dynamicMember:)` and rewrites a member access the type does not declare into a call to it. With a `String` (or any `ExpressibleByStringLiteral`) parameter the compiler passes the name as text, which suits loosely typed data such as a JSON wrapper, but every name compiles, a typo becomes a run-time `null`, and a declared member such as `count` silently wins over the field of the same name. With a `KeyPath`, `WritableKeyPath` or `ReferenceWritableKeyPath` parameter the compiler builds `\Root.name`, so only real members of the root type work, a typo is a compile error, the value keeps its type, and a writable key path with a setter supports assignment. When both subscripts match a name, the key-path one is used, and the string one still catches names the root type lacks.
code
swift · 22 lines@dynamicMemberLookup
enum JSON {
case string(String), number(Double), object([String: JSON]), null
subscript(dynamicMember key: String) -> JSON {
if case .object(let fields) = self { return fields[key] ?? .null }
return .null
}
var count: Int { // a declared member wins over lookup
if case .object(let fields) = self { return fields.count }
return 0
}
}
let payload: JSON = .object([
"user": .object(["name": .string("Ana"), "count": .number(3)])
])
print(payload.user.name) // string("Ana")
print(payload.user.nmae) // null: the typo compiles
print(payload.user.count) // 2: the declared property, not the "count" field
print(payload.user[dynamicMember: "count"]) // number(3.0)go deeper
Recall that the attribute needs a subscript(dynamicMember:) and lets you write value.name for names the type does not declare.
Explain the rewrite into a subscript call, why string lookup lets typos through, and why a declared member with the same name wins.
Build a typed forwarding wrapper with a WritableKeyPath subscript, explain getter and setter calls on compound assignment, and say when string lookup is acceptable.
Judge where dynamic lookup belongs in a codebase: typed forwarding is low risk, while string lookup hides typos and API changes behind dot syntax.
## What the attribute does `@dynamicMemberLookup` can be applied to a class, structure, enumeration or protocol. The type must declare a subscript labelled `dynamicMember`; without one the compiler reports `'@dynamicMemberLookup' requires 'Bad' to have a 'subscript(dynamicMember:)' method that accepts either 'ExpressibleByStringLiteral' or a key path`. When code writes `value.member` and the type has **no declared member** with that name, the compiler rewrites the access as `value[dynamicMember: …]`. What it passes depends on the subscript's parameter type: | Parameter type | What `store.darkMode` becomes | Checked at compile time | |---|---|---| | `String` or another `ExpressibleByStringLiteral` type | `store[dynamicMember: "darkMode"]` | no: any identifier compiles | | `KeyPath<Root, T>` | `store[dynamicMember: \Root.darkMode]` | yes: `Root` must have `darkMode` | | `WritableKeyPath<Root, T>` | the same, and assignment works when the subscript has a setter | yes | | `ReferenceWritableKeyPath<Root, T>` | the same, for a `Root` that is a class | yes | The subscript's return type can be anything. A type may declare both kinds; when both match, the **key-path subscript is used**, because it carries more type information. ## String lookup: a wrapper over loosely typed data The string form fits data whose shape is only known at run time, such as a `JSON` enum decoded from a server payload. `payload.user.name` reads like a property chain but is two subscript calls with the strings `"user"` and `"name"`. The costs: - **Typos compile.** `payload.user.nmae` is accepted and returns whatever the subscript returns for an unknown key, here `.null`. - **Declared members win.** If `JSON` declares `var count: Int`, then `payload.user.count` calls that property, not the `"count"` field. Adding a member later silently changes what existing call sites read. - **The subscript decides the return type.** Here every lookup returns `JSON`, so callers still unwrap the case they expect. For these reasons the string form is best kept to wrappers whose whole purpose is dynamic data, and to types with few declared members. ## Key-path lookup: typed forwarding The key-path form, added in Swift 5.1 (SE-0252), forwards member access to another type while keeping full static checking. A `SettingsStore` class that owns a `Settings` struct can expose `store.darkMode` and `store.fontSize` without declaring either: ```swift struct Settings { var darkMode = false; var fontSize = 14 } @dynamicMemberLookup final class SettingsStore { private(set) var settings = Settings() private(set) var saveCount = 0 subscript<Value>(dynamicMember path: WritableKeyPath<Settings, Value>) -> Value { get { settings[keyPath: path] } set { settings[keyPath: path] = newValue; saveCount += 1 } } } ``` What this gives and what to watch: 1. **Typos are compile errors**: `store.darkMod` fails with `value of type 'SettingsStore' has no dynamic member 'darkMod' using key path from root type 'Settings'`. 2. **Types are preserved**: `store.fontSize` is an `Int`, inferred through the generic `Value`. 3. **Writes need a writable path and a setter.** A `KeyPath` parameter with only a getter makes every forwarded member read-only; a `WritableKeyPath` parameter with `set` allows `store.darkMode = true`, and a compound assignment such as `store.fontSize += 2` performs one `get` and one `set`, so a side effect in the setter runs once per write. 4. **The store's own members still win**: `store.saveCount` reads the property `SettingsStore` declares, and a `Settings` property with the same name would be hidden behind it. ## Chains of dynamic members Each dot is a separate lookup. When the subscript returns the wrapped value's own type, as in the store above, `store.darkMode.description` is one dynamic lookup followed by ordinary member access on a `Bool`. When the subscript returns another wrapper, as a lens or binding-style type does, `lens.origin.x` becomes `lens[dynamicMember: \.origin][dynamicMember: \.x]`: one key path per component, each producing a new wrapper. That is what lets a wrapper project a path into a nested value step by step while keeping every step typed. ## Choosing between them - Use the **string** form only when the member names really are data: a JSON or property-list wrapper, or a bridge to values from a dynamically typed runtime. - Use the **key-path** form to forward to a wrapped value: stores, proxies, and wrappers that should look like the type they hold. - Declaring both is a deliberate fallback: real members of the root go through the key path, unknown names through the string. ## What to remember - The rewrite happens only when no declared member matches the name. - String lookup trades compile-time checking for flexibility; key-path lookup keeps it. - A `WritableKeyPath` subscript with a setter is what makes forwarded properties assignable.
- Why does store.fontSize += 2 trigger the subscript's setter only once?A compound assignment through the dynamic member is a read-modify-write of `store[dynamicMember: \Settings.fontSize]`: the getter returns the current value, the addition happens on that copy, and the setter stores the result once. A persistence side effect in the setter therefore runs once per statement.
- What happens to existing call sites when you add a declared property to a @dynamicMemberLookup type?Any call site that used that name through dynamic lookup now resolves to the declared property instead, with no warning. For a string-based JSON wrapper that can change which value is read, so such types should keep their own declared API small and named so it cannot clash with field names.
- Can a protocol use @dynamicMemberLookup?Yes. The attribute can be applied to a protocol, and conforming types get dynamic member lookup through a `subscript(dynamicMember:)` the protocol requires or a protocol extension provides. This lets several wrapper types share one forwarding behaviour.
- Dynamic member lookup is resolved at run time by reflection over the type.
- With a String subscript, a misspelled member name is a compile error.
- Dynamic lookup takes priority over properties the type declares.
- A KeyPath-based dynamic member is untyped and returns Any.
- Any dynamic member can be assigned to, whatever the subscript declares.