#96: Dynamic Member Lookup in Swift

@dynamicMemberLookup lets a type respond to member access that is resolved through a subscript.

@dynamicMemberLookup
struct DictionaryProxy {
    var storage: [String: String]

    subscript(dynamicMember member: String) -> String? {
        storage[member]
    }
}

let proxy = DictionaryProxy(storage: ["name": "Swift"])
proxy.name

This can be useful for wrappers, scripting bridges and proxy-style APIs.

It is a powerful feature, but because it hides where properties really come from, it is best used with restraint.


I'm also on Twitter and GitHub.

Subscribe via RSS.