swift - 在 Swift 泛型类型中包含继承约束

标签 swift generics

我正在尝试使用 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 没有帮助。

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

最佳答案

一个解决方案。

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

设置一个名为Root的void协议(protocol)

protocol Root {}

使您的根类符合 Root 协议(protocol)

extension YourRootClasses: Root {}

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

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

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

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

关于swift - 在 Swift 泛型类型中包含继承约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52626563/

相关文章:

Javascript 通用 For 循环

swift - 创建 UITextFieldDelegate 以限制 Swift 中的字符数

ios - Swift - UISearchController 与单独的 searchResultsController

Swift 选项需要 nil 吗?无法使用中断?

swift - 红色的 Pods 框架(Xcode 无法识别)

ios - 以编程方式禁用纵向锁定

c# - 在每个类中调用相同方法的最佳方法是什么?

java - Spring Security ACL - @PreAuthorize 泛型和接口(interface)

java - 无法理解 Java 通配符的用法?

c++ - 有没有一种通用的方法可以用 SFINAE 否定 decltype 条件?