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:

  1. Associated Objects
  2. Method Swizzling

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:

Screen Shot 2016-08-07 at 12.28.22 AM

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:

Screen Shot 2016-08-07 at 12.35.41 AM.pngPay 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!!!

Screen Shot 2016-08-07 at 1.29.52 AM



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s