【问题标题】:Unable to create operator for generic class in Swift无法在 Swift 中为泛型类创建运算符
【发布时间】:2018-03-27 17:23:51
【问题描述】:

在 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&lt;T&gt;' to return type 'Self'

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

【问题讨论】:

  • 它看起来像编译器错误。就像,如果你用struct Vector&lt;T&gt; 替换class Vector&lt;T&gt; 它就可以了。也许它与类中的继承有关。
  • 好的,final class 也可以。它肯定会失败,因为类可以被继承并且Self 指向 Vector 或其任何子类。
  • 好的,感谢您的帮助!
  • 这应该写成答案。

标签: swift generics operator-overloading


【解决方案1】:

从 cmets 移出:

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

这个问题的解决方案是:

  • 创建类final,并将返回的Self 设置为正确的类型,这样就可以了
  • class替换为struct,并设置正确的类型
  • 添加associatedtype,默认为Self

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-27
    • 1970-01-01
    • 2016-06-10
    • 1970-01-01
    • 1970-01-01
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多