When using method swizzling in Swift there are two requirements that your classes/methods must comply with:
NSObjectdynamic attributeFor a complete explanation of why this is required, check out Using Swift with Cocoa and Objective-C:
Requiring Dynamic Dispatch
While the
@objcattribute 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 thedynamicmodifier, access to that member is always dynamically dispatched. Because declarations marked with thedynamicmodifier are dispatched using the Objective-C runtime, they’re implicitly marked with the@objcattribute.Requiring dynamic dispatch is rarely necessary. However, you must use the
dynamicmodifier when you know that the implementation of an API is replaced at runtime. For example, you can use themethod_exchangeImplementationsfunction 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.