0

我正在尝试编写一个静态泛型方法,它将协议作为参数并在 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

  1. where Self: P确实编译错误“类型'Self'被限制为非协议,非类类型'P'”
  2. where self: P多次编译错误。
  3. where Self: P.Type确实编译错误“类型'Self'被限制为非协议,非类类型'P.Type'”
  4. where self: P.Type有多个编译错误。

我还想知道我是否可以指定 P 只能是协议的约束。

4

2 回答 2

1

不幸的是,在 Swift 中(还)没有办法定义符合泛型参数的要求,或者要求参数是协议。

这就是 Swinject 的类型转发 API不是类型安全的原因。有一种“技巧”可以让人表达一致性要求,但是我不确定它是否适合您的用例:

extension RegisterableModule {

    static func registerModule<P>(
        asProtocol proto: P.Type, 
        in container: Container, 
        typeCheck: (Self) -> P
    ) {
        container.register(proto) { _ in self.create() as! P }
    }
}

MyModule.registerModule(
    asProtocol: MyProtocol.self, 
    in: container, 
    typeCheck: { $0 }
)
于 2019-02-22T12:35:44.710 回答
0

你能试试吗,我刚刚加了P:SomeProtocol

public extension RegisterableModule {

    static func registerModule<P:SomeProtocol>(asProtocol proto: P.Type,
                                  in container: Container) {
        container.register(proto, name: nil) { (resolver) -> P in
            return self.create()
        }
    }
}
于 2019-02-22T08:30:44.407 回答