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

标签 swift generics

我正在尝试让下面的代码在 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)
    }
}

基本上,我有一个具有关联类型 T 的协议(protocol),以及一个符合该协议(protocol)且具有泛型类型 T 的类,并且我需要实现 ConvertTo 函数,该函数只需将类的类型 T 转换为另一种类型 TNew.T ,该函数应该是 T 的子类。 我已经用 C# 和 Java 等其他语言实现了这个,所以我不确定为什么我不能让它在 Swift 中工作。 我收到以下错误:

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

这就是问题所在。

冒号:用于声明一致性约束,而不是相等性。如果您想使 TNew.TT 两种类型相等,则需要将其重写为 TNew.T == T

关于Swift 泛型类型继承另一个泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37661690/

相关文章:

swift - 无法调用非函数类型的值 "calendar"

ios - 图像重叠 ui 导航栏 swift

c# - 通用子 C# 的通用父级

java - 泛型,传递错误的类型?

ios - 在执行代码之前等待 Swift 动画完成

ios - Carthage:如何获取给定存储库的最新版本?

objective-c - 将 swift 代码桥接到 obj c 项目中

swift - 协议(protocol)不符合自身?

generics - Kotlin:编译器无法为某些运算符推断出通用类型

generics - Ramda 的 Flow 类型中的柯里化(Currying)函数定义