Dynamic Member Lookup in Swift
Dynamic member lookup is a wrapper type around data.
Before starting this article, I’m going to mention Swift’s Attributes.
In one of my recent articles, I mentioned about @ prefix. What’s the future of the @ prefix in Swift? It seems that we will see this more with Attribute properties.
More about Attributes:
https://docs.swift.org/swift-book/ReferenceManual/Attributes.html
Dynamic member lookup is a wrapper type around data. With Dynamic Member Lookup, you can’t be type-checked at compile time.
The key point is Swift is a type-safe language. This means that at compile time you know what the data type is.
For example:
When you define a variable, you must specify its data type.
With Dynamic Member Lookup, you act on the contrary about the data type.
Let’s create an example and reinforce that. I will define a Car struct that holds a name, color, and year data.
Now you can access an item the same as you access properties.
In the above example, what did we learn?
Dynamic Member Lookup attribute enables properties member as Car properties.
If the property we are looking for is not found, the compiler returns the default value that we defined with default=””.
subscript(dynamicMember member: String) method executes all of what we need.
You can access more about subscript here which is I described with code examples:
Also, Dynamic Member Lookup by key path can be used to implement a wrapper type in a way that supports compile-time type checking.
For example:
Now you can access the car fields directly.
print(user.name) // BMW
What are the motivation and contexts of Dynamic Member Lookup? If you are curious about the proposal you can access it here:
And we are here end of the story. That’s it. I hope you find it useful.
In addition, let’s connect on Twitter.
One more thing, last week I added a new feature to more useful to NetGuard open source project that is I developed for the iOS network debugging.
Take a look here: https://github.com/batikansosun/NetGuard