Swizzling is a pretty well known concept thats present in ObjC and Swift has brought it over with it. In a nutshell, swizzling allows the programmer the ability to modify method implementations at runtime. Although not a recommended way of programming day to day tasks, it does have its benefits though.
To a swizzling novice, I highly recommend reading these amazing blog posts by Matt Thompson:
Swift 3.0 has brought with it some very interesting changes. For instance, dispatch_once is not supported now, in addition Swift lifecycle does not call the load() method of a class anymore. Our swizzling code has to take into account these changes. With this in mind, lets take a quick dive into how we should do this.
As a working example, the scenario that I am trying to present here is to print a message in the debugger every time viewWillAppear: is called on any instance of UIViewController in the application.
To do this, I first start with a boilerplate implementation of an extension on UIViewController, which looks like this:
Swift does not call load() method on its class during instantiation, the only available option is to override initialize() and implement the swizzling operation in this method.
Now comes the fun part. Next we should create a function with which you would swizzle viewWillAppear. In this example, I create a function called ai_viewWillAppear that will print the message string in the debugger. The code will now look as such:
Pay attention to the @objc attribute used in the declaration. This makes the swift api available in ObjC runtime.
Here is a complete implementation of how to swizzle in Swift 3.0. The comments are self explanatory. Happy Swizzling!!!