-
-
Save neobeppe/a3a9021299b1ee21afa687c65a762a59 to your computer and use it in GitHub Desktop.
Method injection playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: Playground - noun: a place where people can play | |
import Foundation | |
//Class A implements a method that says its name | |
class ClassA { | |
@objc | |
func hello() { | |
print("Hello, i'm " + String(describing: type(of: self))) | |
} | |
} | |
//Class B is empty | |
class ClassB { } | |
//Inject method from one class in another one | |
func useMethod(sel: Selector, fromClass: AnyClass, inObject: AnyObject) { | |
guard let meth = class_getInstanceMethod(fromClass, sel) else { | |
return | |
} | |
typealias ClosureType = @convention(c) (AnyObject, Selector) -> Void | |
let imp = method_getImplementation(meth) | |
let callMethod: ClosureType = unsafeBitCast(imp, to: ClosureType.self) | |
callMethod(inObject, sel) | |
} | |
//A | |
let a = ClassA() | |
a.hello() | |
//A hello method in B | |
let b = ClassB() | |
useMethod(sel: #selector(ClassA.hello), fromClass:ClassA.self, inObject: b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment