Dynamic Member Lookup in Swift


Greetings, traveler!

The Swift language has many convenient tools to make life easier and code more beautiful. Today, we will discuss one of them: the @dynamicMemberLookup attribute. This feature makes Swift more attractive to developers used to dynamic typing languages such as JavaScript and Python. Still, it maintains the Swift language’s main feature — its type safety.

Example

Consider this example. We have a data store with a property that keeps the dictionary.

final class DataStore {
    var data: [String: Int] = ["Person": 0]
}

We can access data like this.

let dataStore = DataStore()
let person = dataStore.data["Person"]

But we can mark our storage with the @dynamicMemberLookup attribute.

@dynamicMemberLookup
final class DataStore {
    
    var data: [String: Int] = ["Person": 0]
    
    subscript(dynamicMember key: String) -> Int? {
        data[key]
    }
}

And use it like this.

let dataStore = DataStore()
let person = dataStore.person

KeyPath

You can read more about using this attribute with keyPath here. This is a very convenient tool, I can say.

Conclusion

We explored a cool Swift feature — the @dynamicMemberLookup attribute. But there are more hidden gems in this language. The following article will discuss two of them: the callAsFunction method and the @dynamicCallable attribute.