As of Swift 5.1, Swift provides the @_dynamicReplacement modifier to handle method swizzling. Let's find out how to use it!
Method swizzling is a cool feature that allows us to change the implementation of an existing selector at runtime.
If you never heard of it, please check out my previous article. In that article, I’ve explained pretty detail what method swizzling is, how we can use method swizzling, and what we should consider before using it.
Recently while I was developing my project which needed to use Method swizzling, I realized that from Swift 5.1 we have a better native API to achieve method swizzling.
Let’s find out!
Table of contents
What is method swizzling?
Real-world example
New native API to achieve method swizzling
Conclusion
What is method swizzling?
For those who don’t want to read my previous article, here is a brief explanation of method swizzling.
Method swizzling is the process of changing the implementation of an existing selector at runtime.
Real-world example
One of the real-world examples that apply Method swizzling is the famous Pulse framework.
The magic behind Pulse is that Pulse will use a custom URLSession delegate to capture network requests and perform logging.
Here is how Pulse injects its custom URLSession delegate to your URLSession:
New native API to achieve method swizzling
As of Swift 5.1, Swift provides the @_dynamicReplacement modifier to handle method swizzling.
Using the new syntax is simple, just need to follow these steps:
Mark the original function that needs to be replaced with the dynamic modifier.
Use the @_dynamicReplacement modifier upon a replacement function. This modifier takes the original function’s name as a parameter.
The replacement function type must be the same as the original function type.
Sample code:
The cool thing is we don’t need to call any function to perform swizzle. With this modifier, the swizzle will happen when the program starts.
Above is a simple example of how to use @_dynamicReplacement modifier. Let’s try some more complicated example
Conclusion
This new modifier is much nicer compared to the way we need to use objective-c code to swizzle.
Few things to keep in mind:
The @_dynamicReplacement modifier has the underscore syntax, which means it’s not official release. More information here.
@_dynamicReplacement modifier will automatically perform swizzle when the program starts. If you want to perform the swizzle at an arbitrary point in time, you will need to use the old way.