无法在Swift中为泛型类创建运算符

无法在Swift中为泛型类创建运算符,swift,generics,operator-overloading,Swift,Generics,Operator Overloading,在Swift 4中,我创建了以下协议,以确定是否实现了+运算符 protocol Addable { static func +(lhs: Self, rhs: Self) -> Self } 现在我创建了一个名为Vector的类,其中T当然是泛型类型 class Vector<T: Addable>: Addable { var values: [T] init(values: [T]) { self.values = values } static fun

在Swift 4中,我创建了以下协议,以确定是否实现了+运算符

protocol Addable { static func +(lhs: Self, rhs: Self) -> Self }
现在我创建了一个名为
Vector
的类,其中
T
当然是泛型类型

class Vector<T: Addable>: Addable {
 var values: [T]

 init(values: [T]) {
  self.values = values
 }

 static func +(lhs: Vector<T>, rhs: Vector<T>) -> Self {
  return lhs
 }
}
类向量:可添加{
var值:[T]
初始化(值:[T]){
self.values=值
}
静态函数+(左:向量,右:向量)->Self{
返回lhs
}
}
+运算符实现的
返回lhs
部分只是暂时的。但出于某种原因,这给了我以下错误:
无法将“Vector”类型的返回表达式转换为返回类型“Self”

知道我做错了什么吗?我没有任何线索。

从评论中移动:

这个问题是由类的固有性引起的。看起来Swift无法推断非最终类返回的
Self
类型,因为当前类和它的子类中的
Self
的含义不同。但是由于某些原因,参数中的
Self
没有这样的问题

解决这个问题的办法是:

  • 将class
    final
    ,并将returning
    Self
    设置为正确的类型,它将工作
  • class
    替换为
    struct
    ,并设置正确的类型
  • 添加默认情况下为
    Self
    associatedtype

    protocol Addable {
        associatedtype S = Self
        static func + (lhs: Self, rhs: Self) -> S
    }
    
    后一个选项将用于非最终类,但应检查关联类型是否仍然等于
    Self


看起来像是编译器错误。比如,如果用
struct Vector
替换
class Vector
,它就可以正常工作。也许它与类中的继承或其他有关。好的,
final class
也起作用。它肯定会失败,因为类可以被继承,
Self
指向向量或它的任何子类。好的,谢谢你的帮助!这应该写下来作为答案。