简体   繁体   English

从另一个泛型类型继承的Swift泛型类型

[英]Swift generic Type inheriting from another generic type

I am trying to get the code below working in a playground: 我正在尝试让下面的代码在操场上工作:

public protocol SomeTypeProtocol {
    associatedtype T
    func convertTo<TNew:SomeTypeProtocol>()-> TNew
}

public class SomeClass<T>: SomeTypeProtocol{

    var item:T
    public init(item:T)
    {
        self.item = item
    }
    public func convertTo<TNew:SomeTypeProtocol where TNew.T : T>()-> TNew
    {
        return SomeClass<TNew.T>(item: item  as! TNew.T)
    }
}

Basically, I have a protocol with an associated type T, and a class conforming to that protocol with generic type T, and I need to implement the convertTo function that simply converts the class's type T to another type TNew.T which should be a subclass from T. I have this implemented in other languages like C# and Java, so I am not sure why I can't get it working in Swift. 基本上,我有一个具有关联类型T的协议,以及一个与该协议具有通用类型T一致的类,并且我需要实现convertTo函数,该函数将类的类型T简单地转换为另一个类型TNew.T,它应该是一个子类。我已经用C#和Java等其他语言实现了这一点,所以我不确定为什么不能在Swift中使用它。 I am getting the following errors: 我收到以下错误:

1) error: type 'TNew.T' constrained to non-protocol type 'T'
    public func convertTo<TNew:SomeTypeProtocol where TNew.T : T>()-> TNew
2) error: cannot invoke initializer for type 'SomeClass<TNew.T>' with an argument list of type '(item: TNew.T)'
        return SomeClass<TNew.T>(item: item as! TNew.T)

3) note: expected an argument list of type '(item: T)'
        return SomeClass<TNew.T>(item: item as! TNew.T)

4)note: protocol requires nested type 'T'
    associatedtype T

TNew.T : T

This is where the problem lies. 这就是问题所在。

The colon, : , is used to declare a conformance constraint, not equality. 冒号: ,用于声明一致性约束,而不是相等性。 You need to rewrite this as TNew.T == T if you want to equate the two types TNew.T and T . 如果要将TNew.TT两种类型等同,则需要将其重写为TNew.T == T

I believe the closest you can get to doing something like that is this: 我相信您可以做的最接近的事情是这样的:

public func convertTo<TNew where TNew : T>()-> SomeClass<TNew>
{
    return SomeClass<TNew>(item: item  as! TNew)
}

But I don't believe you can't enforce it being only a subclass and not the same class. 但是我不相信您不能仅将其强制为子类而不是同一类。

Be careful doing this type of thing with generics. 使用泛型执行此类操作时要小心。 If you're needing to constantly change the Type of your generic, you might want to consider using a different design. 如果您需要不断更改泛型的类型,则可能需要考虑使用其他设计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM