假设我在名为Registry的模块中定义了一个注册表:
class Registry {
static let sharedInstance = Registry()
registerImplementation(implementation: AnyClass, forInterface interface: Protocol) {...}
implementationForInterface(interface: Protocol) -> AnyClass {...}
}
分别在模块FooServiceAPI和FooServiceImplementation中的API和实现。
// In FooServiceAPI target:
protocol FooService {
...
}
// In FooServiceImplementation target:
import FooServiceAPI
import Registry
// This line causes an error saying that code cannot be executed at the top level.
Registry.sharedInstance.registerInterface(FooService, forImplementation: FooServiceImplementation)
class FooServiceImplementation: FooService {
...
}
我希望FooServiceImplementation在FooServiceAPI接口的Registry中自动注册,以便其他类可以像这样使用它们:
import Registry
import FooServiceAPI
class Bar {
func baz() {
let fooService: FooService = Registry.sharedInstance.implementationForInterface(FooService)
...
}
}
如何在不强制应用程序单独注册AppDelegate中的实现的情况下完成此操作?谢谢!