InterposeKit
InterposeKit is a modern library to swizzle elegantly in Swift. It is well-documented, tested, written in “pure” Swift 5.2 and works on
@objc dynamicSwift functions or Objective-C instance methods. The Inspiration for InterposeKit was a race condition in Mac Catalyst, which required tricky swizzling to fix, I also wrote up implementation thoughts on my blog.Instead of adding new methods and exchanging implementations based on
method_exchangeImplementations, this library replaces the implementation directly usingclass_replaceMethod. This avoids some of the usual problems with swizzling.You can call the original implementation and add code before, instead or after a method call.
imp_implementationWithBlockhas no way to undo or deregister the IMP; so once you submitted a block that captures state, you have a permanent memory leak? Oh well.