Skip to content

Instantly share code, notes, and snippets.

@ygweric
Created November 28, 2016 22:11
Show Gist options
  • Save ygweric/c1b6399fce8296174353ce1a74406488 to your computer and use it in GitHub Desktop.
Save ygweric/c1b6399fce8296174353ce1a74406488 to your computer and use it in GitHub Desktop.
Swizzle for class method and instance method with Swift
func swizzleClassMethod(cls: AnyClass, oldSelector: Selector, newSelector: Selector) {
let oldMethod = class_getClassMethod(cls, oldSelector)
let newMethod = class_getClassMethod(cls, newSelector)
method_exchangeImplementations(oldMethod, newMethod)
// following code not work
// if(class_addMethod(cls, oldSelector, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))) {
// class_replaceMethod(cls, newSelector, method_getImplementation(oldMethod), method_getTypeEncoding(oldMethod))
// } else {
// method_exchangeImplementations(oldMethod, newMethod)
// }
}
func swizzleInstanceMethod(cls: AnyClass, oldSelector: Selector, newSelector: Selector) {
let oldMethod = class_getInstanceMethod(cls, oldSelector)
let newMethod = class_getInstanceMethod(cls, newSelector)
if(class_addMethod(cls, oldSelector, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))) {
class_replaceMethod(cls, newSelector, method_getImplementation(oldMethod), method_getTypeEncoding(oldMethod))
} else {
method_exchangeImplementations(oldMethod, newMethod)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment