@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:
- Attribute Definition: You mark a type (such as a struct or class) with
@dynamicMemberLookup
. - 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: ""]
}
}
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
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!
Read more
- Pull-to-Refresh in SwiftUI • 2 minutes reading time.
- New Website • 2 minutes reading time.
- async/await • 6 minutes reading time.
Share
Share Mastodon Twitter LinkedIn Facebook