Skip to content

Instantly share code, notes, and snippets.

@vlondon
Created March 21, 2017 10:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vlondon/e0fcb728c6a963e31b288adb79dbfc22 to your computer and use it in GitHub Desktop.
Save vlondon/e0fcb728c6a963e31b288adb79dbfc22 to your computer and use it in GitHub Desktop.
Swizzling in Swift 3
import Foundation
// Swizzling
extension NSObject {
class func swizzleMethods(origSelector: Selector, withSelector: Selector, forClass: AnyClass) {
let originalMethod = class_getInstanceMethod(forClass, origSelector)
let swizzledMethod = class_getInstanceMethod(forClass, withSelector)
method_exchangeImplementations(originalMethod, swizzledMethod)
}
func swizzleMethods(origSelector: Selector, withSelector: Selector) {
let aClass: AnyClass! = object_getClass(self)
NSObject.swizzleMethods(origSelector: origSelector, withSelector: withSelector, forClass: aClass)
}
}
import UIKit
// Use Swizzling
public extension UIColor {
func colorDescription() -> String {
return "Some Custom text Here"
}
public class func swizzleDesription() {
let instance = UIColor.red
instance.swizzleMethods(origSelector: #selector(UIColor.colorDescription), withSelector: #selector(getter: NSObjectProtocol.description))
}
}
// Somewhere in the Project
UIColor.swizzleDesription()
print(UIColor.red)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment