我正在尝试让下面的代码在 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.T
和 T
两种类型相等,则需要将其重写为 TNew.T == T
。
关于Swift 泛型类型继承另一个泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37661690/