Skip to content

Instantly share code, notes, and snippets.

@bannzai
Created July 16, 2019 17:26
Show Gist options
  • Save bannzai/7efa8ed932a431f3bb70a2bd9a1704f3 to your computer and use it in GitHub Desktop.
Save bannzai/7efa8ed932a431f3bb70a2bd9a1704f3 to your computer and use it in GitHub Desktop.
init swizzling for swift.
public class Model: NSObject {
@objc dynamic init(x: Int) {
print("x: \(x)")
}
@objc dynamic init(y: Int) {
print("y: \(y)")
}
}
func swizzle() {
let fromSelector = #selector(Model.init(x:))
let toSelector = #selector(Model.init(y:))
let from = class_getInstanceMethod(Model.self, fromSelector)!
let to = class_getInstanceMethod(Model.self, toSelector)!
method_exchangeImplementations(from, to)
}
swizzle()
_ = Model.init(x: 1) // y: 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment