When using method swizzling in Swift there are two requirements that your classes/methods must comply with:
NSObject
dynamic
attributeFor a complete explanation of why this is required, check out Using Swift with Cocoa and Objective-C:
Requiring Dynamic Dispatch
While the
@objc
attribute exposes your Swift API to the Objective-C runtime, it does not guarantee dynamic dispatch of a property, method, subscript, or initializer. The Swift compiler may still devirtualize or inline member access to optimize the performance of your code, bypassing the Objective-C runtime. When you mark a member declaration with thedynamic
modifier, access to that member is always dynamically dispatched. Because declarations marked with thedynamic
modifier are dispatched using the Objective-C runtime, they’re implicitly marked with the@objc
attribute.Requiring dynamic dispatch is rarely necessary. However, you must use the
dynamic
modifier when you know that the implementation of an API is replaced at runtime. For example, you can use themethod_exchangeImplementations
function in the Objective-C runtime to swap out the implementation of a method while an app is running. If the Swift compiler inlined the implementation of the method or devirtualized access to it, the new implementation would not be used.