我正在尝试编写一个静态泛型方法,它将协议作为参数并在 Swinject 容器中注册类实例作为协议解析。重要的是我不能将模块注册为它不符合的协议。
我写了这样的东西:
/// RegisterableModule guarantee that conformer has `create()` method returning self
public extension RegisterableModule {
static func registerModule<P>(asProtocol proto: P.Type,
in container: Container) {
container.register(proto, name: nil) { (resolver) -> P in
return self.create()
}
}
}
它不能编译,因为显然 Self 可能不符合 P
我还尝试使用以下方法指定通用约束where
:
where Self: P
确实编译错误“类型'Self'被限制为非协议,非类类型'P'”where self: P
多次编译错误。where Self: P.Type
确实编译错误“类型'Self'被限制为非协议,非类类型'P.Type'”where self: P.Type
有多个编译错误。
我还想知道我是否可以指定 P 只能是协议的约束。