【问题标题】:Include inheritance constraint in Swift Generic types在 Swift 泛型类型中包含继承约束
【发布时间】:2018-10-03 11:58:46
【问题描述】:

我正在尝试使用 Swift 和泛型创建一个基本的服务定位器/DI 实现。我想要完成的是注册 typeimplementation-type 并将这两个限制在签名中,以便派生 implementation-type来自类型

但是我似乎无法提出正确的语法(如果可能的话)。我天真的尝试:

func register<T, U>(type: T.Type, implementationType: U.Type) where U: T {
    // ...
}

然而,这不会编译,并带有以下消息:

Type 'U' constrained to non-protocol, non-class type 'T'

添加约束where T: AnyObject,没有帮助。

是否可以在签名中限制继承?

【问题讨论】:

    标签: swift generics


    【解决方案1】:

    一个解决方案。

    我想你有一些类,其中很少有其他类的根,你的“抵抗”功能的客户。

    设置一个名为 Root 的无效协议

    protocol Root {}
    

    使您的根类符合协议 Root

    extension YourRootClasses: Root {}
    
    eg: 
    class A: Root {} ; class B: A {}
    class Mainstuff: Root {} ; class SubStuff: MainStuff
    

    然后您可以检查通用 U 到 Root 协议的一致性或继承性。

    func register<T, U>(type: T.Type, implementationType: U.Type) where U: Root {
    // ...
    }
    

    确实,如果你有 A -> B -> C 并且想严格检查 C -> B,那是行不通的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多