Skip to content

Instantly share code, notes, and snippets.

@devxoul
Last active September 22, 2020 08:26
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 devxoul/e153b96c5e7c7dbc94d7fa4916b4bf07 to your computer and use it in GitHub Desktop.
Save devxoul/e153b96c5e7c7dbc94d7fa4916b4bf07 to your computer and use it in GitHub Desktop.
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