Skip to content

Instantly share code, notes, and snippets.

@efremidze
Created November 21, 2017 23:10
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 efremidze/c55f710b1d76825247bb394eda1d179b to your computer and use it in GitHub Desktop.
Save efremidze/c55f710b1d76825247bb394eda1d179b to your computer and use it in GitHub Desktop.
import ObjectiveC.runtime
// https://codelle.com/blog/2016/2/calling-methods-from-strings-in-swift/
func extractMethod(_ owner: AnyObject, _ selector: Selector) -> ((Any?, Any?) -> AnyObject)? {
guard let method = getMethod(owner, selector) else { return nil }
let imp = method_getImplementation(method)
typealias CFunction = @convention(c) (AnyObject, Selector, Any?, Any?) -> Unmanaged<AnyObject>
let function = unsafeBitCast(imp, to: CFunction.self)
return { arg1, arg2 in function(owner, selector, arg1, arg2).takeUnretainedValue() }
}
private func getMethod(_ owner: AnyObject, _ selector: Selector) -> Method? {
if let owner = owner as? AnyClass {
return class_getClassMethod(owner, selector)
} else {
return class_getInstanceMethod(type(of: owner), selector)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment