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( // 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(“\nswizzled\n”)print(“\nTrying to swizzle again\n”)print(}
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 🤨