Method swizzling in iOS swift

What is method swizzling ?? — this was a question asked in an interview. I didn’t knew the answer back then. I googled it and found many articles about method swizzling. But, I couldn’t understand the proper use case of method swizzling. Michael Mavris’s article on method swizzling was simple and easy to understand. Read it here.

What is method swizzling?

How to do method swizzling in swift 4?

Let’s swizzle!!

print(UIColor.red) // prints UIExtendedSRGBColorSpace 1 0 0 1
import Foundationimport UIKitpublic extension UIColor {@objc func colorDescription() -> String {return "Printing rainbow colours."}private static let swizzleDesriptionImplementation: Void = {let instance: UIColor = UIColor.redlet aClass: AnyClass! = object_getClass(instance)let originalMethod = class_getInstanceMethod(aClass, #selector(description))let swizzledMethod = class_getInstanceMethod(aClass, #selector(colorDescription))if let originalMethod = originalMethod, let swizzledMethod = swizzledMethod {
// switch implementation..
method_exchangeImplementations(originalMethod, swizzledMethod)
}}()public static func swizzleDesription() {_ = self.swizzleDesriptionImplementation}}
override func viewDidLoad() {super.viewDidLoad()print(UIColor.red)print(UIColor.green)UIColor.swizzleDesription()print(“\nswizzled\n”)print(UIColor.red)print(UIColor.red)UIColor.swizzleDesription()print(“\nTrying to swizzle again\n”)print(UIColor.red)print(UIColor.red)}
UIExtendedSRGBColorSpace 1 0 0 1UIExtendedSRGBColorSpace 0 1 0 1swizzledPrinting rainbow colours.Printing rainbow colours.Trying to swizzle againPrinting rainbow colours.Printing rainbow colours.

Drawbacks of method swizzling

If you enjoyed reading this post, please share and give some clapps so others can find it 👏👏👏👏👏 !!!!

iOS and tvOS developer, dreamer, photographer 🤨

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store