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



在 Swift 4 中,我创建了以下协议来确定某些东西是否具有 + 运算符

protocol Addable { static func +(lhs: Self, rhs: Self) -> Self }

现在,我创建了一个名为 Vector<T> 的类,其中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
 }
}

+ 运算符实现的return lhs部分只是暂时的。但是由于某种原因,这给了我以下错误: Cannot convert return expression of type 'Vector<T>' to return type 'Self'

知道我在这里做错了什么吗?我一点头绪都没有。

从评论中移出:

问题是由阶级不可避免性引起的。看起来 Swift 无法推断非最终类的返回Self类型,因为当前类中的Self和它的子类意味着不同。但是由于某种原因,参数中的Self没有这样的问题。

这个问题的解决方案是:

  • 将类设置为final,并将返回Self设置为正确的类型,它将起作用
  • class替换为struct,并设置正确的类型
  • 添加默认Self associatedtype

    protocol Addable {
        associatedtype S = Self
        static func + (lhs: Self, rhs: Self) -> S
    }
    

    后一个选项适用于非最终类,但应检查关联的类型是否仍然等于 Self

最新更新