Skip to content

Instantly share code, notes, and snippets.

@creasty
Created September 12, 2018 06:49
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 creasty/a7f129b81153dd5640d6dccf4cdd2750 to your computer and use it in GitHub Desktop.
Save creasty/a7f129b81153dd5640d6dccf4cdd2750 to your computer and use it in GitHub Desktop.
import Foundation
public struct Swizzle {
private init() {}
public static func classMethod(_ cls: AnyClass, to: Selector, from: Selector) {
let cls: AnyClass = object_getClass(cls)!
let toMethod = class_getInstanceMethod(cls, to)
let fromMethod = class_getInstanceMethod(cls, from)
if class_addMethod(cls, from, method_getImplementation(toMethod!), method_getTypeEncoding(toMethod!)) {
class_replaceMethod(cls, to, method_getImplementation(fromMethod!), method_getTypeEncoding(fromMethod!))
} else {
method_exchangeImplementations(fromMethod!, toMethod!)
}
}
public static func instanceMethod(_ cls: AnyClass, to: Selector, from: Selector) {
let toMethod = class_getInstanceMethod(cls, to)
let fromMethod = class_getInstanceMethod(cls, from)
if class_addMethod(cls, from, method_getImplementation(toMethod!), method_getTypeEncoding(toMethod!)) {
class_replaceMethod(cls, to, method_getImplementation(fromMethod!), method_getTypeEncoding(fromMethod!))
} else {
method_exchangeImplementations(fromMethod!, toMethod!)
}
}
}
class Foo: NSObject {
@objc static var staticVar: String {
return "original"
}
@objc static func staticFunc() -> String {
return "original"
}
@objc var instanceVar: String {
return "original"
}
@objc func instanceFunc() -> String {
return "original"
}
//}
//
//extension Foo {
@objc static var newStaticVar: String {
return "new"
}
@objc static func newStaticFunc() -> String {
return "new"
}
@objc var newInstanceVar: String {
return "new"
}
@objc func newInstanceFunc() -> String {
return "new"
}
}
Swizzle.classMethod(
Foo.self,
to: #selector(getter: Foo.newStaticVar),
from: #selector(getter: Foo.staticVar)
)
Swizzle.classMethod(
Foo.self,
to: #selector(Foo.newStaticFunc),
from: #selector(Foo.staticFunc)
)
Swizzle.instanceMethod(
Foo.self,
to: #selector(getter: Foo.newInstanceVar),
from: #selector(getter: Foo.instanceVar)
)
Swizzle.instanceMethod(
Foo.self,
to: #selector(Foo.newInstanceFunc),
from: #selector(Foo.instanceFunc)
)
print(Foo.staticVar)
print(Foo.staticFunc())
print(Foo().instanceVar)
print(Foo().instanceFunc())
print(Foo.newStaticVar)
print(Foo.newStaticFunc())
print(Foo().newInstanceVar)
print(Foo().newInstanceFunc())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment