TheDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
@dynamicMemberLookup attribute instructs the Swift compiler to invoke a custom subscript method when a property is accessed that is not explicitly declared on the type. It bridges static type checking with dynamic runtime behavior by translating arbitrary dot-syntax property accesses into subscript calls.
To satisfy the attribute’s requirements, the annotated type (class, struct, enum, or protocol) must implement at least one subscript(dynamicMember:) method. The compiler intercepts unresolved property accesses and rewrites them to pass the property identifier as the argument to this subscript.
Swift supports two distinct mechanisms for dynamic member lookup: String-based and KeyPath-based.
String-Based Lookup
In String-based lookup, the compiler passes the name of the accessed property as a string literal. This approach bypasses compile-time property validation, deferring resolution entirely to runtime. The parameter accepted by the subscript must beString or a type that conforms to the ExpressibleByStringLiteral protocol.
Syntax:
KeyPath-Based Lookup
KeyPath-based lookup allows a type to dynamically expose the properties of another type while maintaining strict compile-time type safety. Instead of passing a string, the compiler passes aKeyPath (or WritableKeyPath, ReferenceWritableKeyPath) pointing to a property on a wrapped or associated type.
Syntax:
WrappedType and enforces the correct return type T.
Overloading and Resolution Rules
You can overload thesubscript(dynamicMember:) method within the same type. The Swift compiler resolves the appropriate subscript using standard overload resolution rules based on:
- Argument Type: Whether the lookup can be satisfied by a
KeyPathor requires falling back to aString(orExpressibleByStringLiteraltype). - Return Type: If multiple String-based subscripts exist returning different types, the compiler infers the correct subscript based on the type context of the assignment.
- Mutability: The compiler will select a
WritableKeyPathsubscript over a read-onlyKeyPathsubscript if the property access is a mutation (e.g., the left-hand side of an assignment).
Master Swift with Deep Grasping Methodology!Learn More





