在Swift泛型类型中包含继承约束 [英] Include inheritance constraint in Swift Generic types

查看:180
本文介绍了在Swift泛型类型中包含继承约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Swift和泛型创建一个基本的Service Locator/DI实现.我要完成的工作是注册 type implementation-type 并在签名中约束这两个,以便派生 implementation-type 来自 type .

I'm trying to create a basic Service Locator / DI implementation using Swift and generics. What I want to accomplish is registering type and implementation-type and have those two constrained in the signature, so that the implementation-type is derived from the type.

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

However I cannot seem to come up with the correct syntax (if at all possible). My naive attempt:

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

这将无法编译,并显示以下消息:

This will not compile however, with the message:

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

添加约束where T: AnyObject并没有帮助.

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

Is it at all possible to constrain the inheritance in the signature?

推荐答案

解决方案.

我想像一下您有一些类,而其中的一些类却不是其他类的根,它们是您的"resister"功能的客户.

I image you have some classes, with few of them root of others, customers of your "resister" function.

设置名为Root的无效协议

Set up a void protocol named Root

protocol Root {}

使根类符合协议根

extension YourRootClasses: Root {}

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

然后,您可以检查通用U到Root协议的符合性或继承性.

then you can check the conformance or inheritance of your generic U to Root protocol.

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

的确,如果您有A-> B-> C并要严格检查C-> B,那么它是行不通的.

It's true that if you have A -> B -> C and want check C -> B strictly, it doesn't work.

这篇关于在Swift泛型类型中包含继承约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆