DEV Community

Wesley de Groot
Wesley de Groot

Posted on • Originally published at wesleydegroot.nl on

@dynamicMemberLookup

Let's delve into the fascinating world of Swift's @dynamicMemberLookup. This attribute, introduced in Swift 4.2, provides a powerful mechanism for accessing properties and methods dynamically even those that aren't known until runtime.

What is @dynamicMemberLookup?

At its core, @dynamicMemberLookup instructs Swift to call a subscript method when accessing properties.

This method, called subscript(dynamicMember:), is required. Here's how it works:

  1. Attribute Definition : You mark a type (such as a struct or class) with @dynamicMemberLookup.
  2. Subscript Method : You implement the subscript(dynamicMember:) method within that type. This method takes a string parameter representing the name of the requested property and returns any value you like.

Use Case: Dynamic Properties

Let's make a simple example. Imagine we have a Person struct that reads its values from a dictionary:

@dynamicMemberLookup
struct Person {
    private let properties = [
        "name": "Wesley de Groot",
        "city": "Haarlem"
    ]

    subscript(dynamicMember member: String) -> String {
        return properties[member, default: ""]
    }
}
Enter fullscreen mode Exit fullscreen mode

In this case:

  • The @dynamicMemberLookup attribute ensures that our type handles dynamic member lookup.
  • The subscript(dynamicMember:) method looks up the member name in the dictionary and returns its value.

Now, we can access properties that don't actually exist as direct properties on the Person type:

let wesley = Person()
print(wesley.name) // Prints "Wesley de Groot"
print(wesley.city) // Prints "Haarlem"
print(wesley.pet) // Prints an empty string
Enter fullscreen mode Exit fullscreen mode

Even though name, city, and pet are not actual properties, they are looked up at runtime.

This feature bridges the gap between Swift's strong type safety and the more relaxed behavior of dynamic languages like PHP and JavaScript.

Conclusion

@dynamicMemberLookup is a powerfull attribute to create easier to read code, it can be used on arrays and therefore also for JSON!

Resources: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/attributes#dynamicMemberLookup

Top comments (0)