@dynamicMemberLookup
Build dynamic, type-safe member access.
What Is Dynamic Member Lookup?
The @dynamicMemberLookup attribute lets a type respond to dot-syntax member access that is not declared as a real property. When you write value.something, Swift routes it to a special subscript you define.
This gives wrapper types a natural feel while keeping the access in one place.
@dynamicMemberLookup
struct Settings {
private var storage: [String: String] = ["theme": "dark"]
subscript(dynamicMember key: String) -> String? {
storage[key]
}
}
let s = Settings()
print(s.theme ?? "none")The Required Subscript
A type marked @dynamicMemberLookup must implement subscript(dynamicMember:). When the parameter is a String, the member name you type becomes that string at runtime.
So config.timeout calls the subscript with the key "timeout".
@dynamicMemberLookup
struct Config {
let values: [String: Int]
subscript(dynamicMember member: String) -> Int {
values[member] ?? 0
}
}
let config = Config(values: ["timeout": 30, "retries": 3])
print(config.timeout)
print(config.retries)All lessons in this course
- KeyPath Basics
- Using KeyPaths in Collections
- Writable and Reference KeyPaths
- @dynamicMemberLookup