Member-only story

Dynamic Member Lookup in Swift

Use this with strings and keypaths

Artturi Jalli
2 min readMay 6, 2021
Drawing of code on device
Photo by the author.

Dynamic member lookup improves interoperability with dynamic languages such as Python, Javascript, Ruby, etc.

It allows you to look at values from a dictionary with a syntax similar to when accessing a regular property of a type. For example, you can replace dog.props["color"] with just dog.color.

How To Enable Dynamic Member Lookup

To use dynamic member lookup, tag a type you have created with @dynamicMemberLookup and implement a subscript(dynamicMember:) method. This method takes either a string or a keypath argument.

Let me show you both of these cases with practical examples.

Example 1: Dynamic member lookup with strings

As a first example, let’s create an Animal structure that supports dynamic member lookup by implementing the subscript method with a string argument.

The whole point of this example is to be able to call dog.color to look up a value from a dictionary instead of calling dog.props["color"] like you’d probably expect.

The implementation of the Animal structure that supports dynamic member lookup is pretty straightforward:

--

--

No responses yet

Write a response