Introspect and modify classes at runtime in your Swift app
Remember the big Dynamism-in-Swift debate of May 2016? If not, here’s a quick refresher:
Brent Simmons (see archive for more): In case it's not clear: with recent and future articles I'm documenting problems…mjtsai.com
In short, the argument is that there are many types of problems that developers are currently solving with the dynamic features of the ObjC runtime. As we are (possibly) heading towards a future where Swift replaces Objective C completely, Swift will need to provide its own native dynamic solutions.
On iOS and macOS, for the foreseeable future at least, Swift will run on top of the Objective C runtime and this means we have full access to these functionalities. Sadly, they are a real pain to use in Swift. We can make it better…
ObjectiveKit is a new Swift framework for accessing Objective C runtime functions.
It makes things like introspection, modifying methods and creating classes at runtime super easy in a way that feels as native as possible to Swift.
How does it work? All you need to do is initialise an ObjectiveClass object that is typed to the class that you want to introspect/modify, then use one of ObjectiveKit’s many functions. Here’s a quick example:
Playing around with the Objective C runtime is both fun, educational and super useful for debugging. However, it is also dangerous — please exercise extreme caution before using it in production.