Last active
September 22, 2020 08:26
-
-
Save devxoul/e153b96c5e7c7dbc94d7fa4916b4bf07 to your computer and use it in GitHub Desktop.
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
import Foundation | |
public enum Swinject { | |
public final class Container { | |
} | |
} | |
protocol Assembly { | |
func assemble(to container: Swinject.Container) | |
} | |
@objcMembers public class AutoAssembly: NSObject, Assembly { | |
public class Container: NSObject { | |
let container: Swinject.Container | |
init(container: Swinject.Container) { | |
self.container = container | |
} | |
} | |
public func assemble(to container: Swinject.Container) { | |
var count: UInt32 = 0 | |
guard let methods = class_copyMethodList(Self.self, &count) else { return } | |
let container = Container(container: container) | |
for i in 0..<count { | |
let pointer = methods.advanced(by: Int(i)) | |
let method = pointer.pointee | |
let selector = method_getName(method) | |
let name = NSStringFromSelector(selector) | |
guard name.hasPrefix("register") else { continue } | |
let implementation = method_getImplementation(method) | |
typealias ObjcRegisterBlock = @convention(c) (Any, Selector, Container) -> Void | |
let register = unsafeBitCast(implementation, to: ObjcRegisterBlock.self) | |
register(self, selector, container) | |
} | |
} | |
} | |
public class MyAssembly: AutoAssembly { | |
func registerFoo(to container: Container) { | |
print(#function) | |
} | |
func registerBar(to container: Container) { | |
print(#function) | |
} | |
} | |
let container = Swinject.Container() | |
MyAssembly().assemble(to: container) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment