Talk is cheap, show me the code!

Hi, I'mBhavik Thummar

iOS Developer & Designer

Download Resume

Method Swizzling in Swift

I was recently introduced to method swizzling in Swift. This allows the implementation for a selector (i.e., method) to be changed as a program executes. Method swizzling is the act of swapping the implementations of two selectors as a program runs. This dynamic program modification is similar to monkey patching, a concept supported by other dynamic languages.

Most of the use cases I’ve found for method swizzling involve extending the functionality of an existing method. That is, there is some method (e.g., viewDidLoad.) that you can’t modify directly, but would like to add additional functionality too.

Let’s see some use cases of Method Swizzling


I want to do something before all of my ViewController’s viewWillAppear,
Like,

  • I need to display an alert to the user If the auth token expires and the user has to Re-Login
  • I need to display an offer to the user as a Banner whatever may be the screen that user presently is in.

In these cases, Actually, we can go with a Base class and write our logic in the Base class.

But this is not the correct approach.

Because, We need to write Base classes for not only UIViewController, But also for UITableViewController, UINavigationController, UITabBarController and all which we use in our app.

If we go with Base classes, Our code will be redundant and there will be multiple base classes for the same piece of code.

Let’s see how that can be solved using Method Swizzling


Take an extension of UIViewController and apply swizzling for its viewWillAppear method.

Here, I am swapping, viewWillAppear with my custom Method newViewWillAppear using method_exchangeImplementations, Which is from Objective-C runtime.

Where we will have the notification logic.

Now, In the child classes of UIViewControllers, super.ViewWillAppear, Calls the newViewWillAppear.

The beauty here is, The same will get called for UITableViewController and UINavigationController also as they are also extended from UIViewController.

Thus, Using Method Swizzling, There will not be any code redundancy.

Unlike in Swift3x, In swift 4, We can not write this swizzling the initialise method, And we can call it in AppDelegate.

So, Whenever app launches, This swizzling applies and stays.
Hope this post is useful. Feel free to comment in case of any queries.

  • Share this :

Leave a comment