Swift Underrated Technique — Method Swizzling

Samrith Yoeun
Mac O’Clock
Published in
2 min readMay 7, 2020

--

Have you ever encounter the term ‘method swizzling’ before?

My first encounter with this strange term was when I tried to implement Firebase Cloud Messaging, and I was like what the hell is ‘Method Swizzling’

I have been to quite a few Job Interviews, nobody ask me about method swizzling, some of my interviewees don’t even know how to write ’swizzling’ when I asked them if they have heard of it.but never mind I will tell you about this quite underrated mechanism today.

Method swizzling is the process of changing the implementation of an existing selector. It’s a technique made possible by the fact that method invocations in Objective-C can be changed at runtime, by changing how selectors are mapped to underlying functions in a class’s dispatch table.

Simple word,

it is a technique that allow developer to change the existing method definition in runtime.

You may ask why would you use it, and why I said this mechanism is quite underrated, allow me to talk about it in the next seconds…

Method swizzling allow you to:

  • change the existing method definition
  • call the same method signature with modified behavior/ action/ code
  • write less complicate code and remember method signature easily

Swizzling method is quite underrated:

For example:

in the iOS 13 , Apple change the default UIModelPresentation from .fullscreen to .pagesheet, but most UI/UX designs was not ready this change yet.

To solve this issue you can either:

  • Use extension and create your own ‘present’ method
  • Have a child class of UIViewController and override the ‘present’ method
  • OR use method swizzling

I will show you how to use Method Swizzling to resolve the issue. Please follow these 3 simple steps:

1.Create a new method

This method is used to change UIModelPresentation from .pagesheet or .automatic to .fullscreeen, (in this case it is named as ‘shouldPresent’), and I placed it in UIViewController extension

2.Create Method Swizzling:

This method is used to change how selectors are mapped to underlying functions in a class’s dispatch table. In simple word, change the existing method definition in runtime.

3. Tell the application on when should Method Swizzling works its magic:

Most of the time we put the method Method Swizzling after the application is loaded, so let’s put it in didFinishedLaunching

Horray, It is done!

Now you can finally see Method Swizzling magic, huh.

I hope you enjoy reading this post and if you want to check the full source code, come here!

--

--