0Pricing
Swift Academy · Lesson

@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

  1. KeyPath Basics
  2. Using KeyPaths in Collections
  3. Writable and Reference KeyPaths
  4. @dynamicMemberLookup
← Back to Swift Academy