★ Replacement of viewWillAppear method
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)")
}
}
★ Replacement of NSObjectProtocol.description method
import UIKit
import ObjectiveC
extension NSObject {
func swizzDescription() -> String {
print("swizzed")
return self.swizzDescription()
}
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
override class func initialize() {
let m1 = class_getInstanceMethod(NSObject.self, #selector(getter: NSObjectProtocol.description))
let m2 = class_getInstanceMethod(NSObject.self, #selector(NSObject.swizzDescription))
method_exchangeImplementations(m1, m2)
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
print(self)
return true
}
}
★ Original: KentarouKanno/Method Swizzling.md