My question is not about how to swizzle, but rather what is happening in this particular code snippet:
private let swizzling: (UIViewController.Type) -> () = { viewController in
let originalSelector = #selector(viewController.viewWillAppear(_:))
let swizzledSelector = #selector(viewController.proj_viewWillAppear(animated:))
let originalMethod = class_getInstanceMethod(viewController, originalSelector)
let swizzledMethod = class_getInstanceMethod(viewController, swizzledSelector)
method_exchangeImplementations(originalMethod, swizzledMethod) }
extension UIViewController {
open override class func initialize() {
// make sure this isn't a subclass
guard self === UIViewController.self else { return }
swizzling(self)
}
// MARK: - Method Swizzling
func proj_viewWillAppear(animated: Bool) {
self.proj_viewWillAppear(animated: animated)
let viewControllerName = NSStringFromClass(type(of: self))
print("viewWillAppear: \(viewControllerName)")
}
}
This code sniper is from here: Swizzling CocoaTouch class
The question I have is around the following line of code:
// make sure this isn't a subclass
guard self === UIViewController.self else { return }
Why do we need to check if it isn't a subclass of UIViewController? My scenario is I want to send analytics data with view name to Omniture (on ever viewWillAppear). If I do the check, the swizzling never works, yet when I comment this line out, I get my desired result, and every view controller sends data.