Skip to content

Instantly share code, notes, and snippets.

@alexkent
Created August 20, 2014 07:59
Show Gist options
  • Save alexkent/1074a03879df7766450c to your computer and use it in GitHub Desktop.
Save alexkent/1074a03879df7766450c to your computer and use it in GitHub Desktop.
import Cocoa
class Thing:NSObject {
func a() {
println("a")
}
}
extension Thing {
// func a() {
// println("a")
// }
}
extension Thing {
func b() {
println("b")
}
}
func exchangeMethods(classType:AnyClass, methodName:String, swizzleName:String) {
let method: Method = class_getInstanceMethod(classType, Selector.convertFromStringLiteral(methodName))
let swizzleMethod: Method = class_getInstanceMethod(classType, Selector.convertFromStringLiteral(swizzleName))
assert(method != nil, "Unable to find method to replace")
assert(swizzleMethod != nil, "Unable to find replacung method")
method_exchangeImplementations(method, swizzleMethod)
}
let foo = Thing()
foo.a()
foo.b()
println("")
exchangeMethods(Thing.self, "a", "b")
foo.a()
foo.b()
/// Output
// a
// b
//
// a
// a
/// Comment out the a() implementation in the class body and uncomment the a() implementation in the extension
/// Output
// a
// b
//
// b
// a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment