【发布时间】: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<T>' to return type 'Self'
知道我在这里做错了什么吗?我没有头绪。
【问题讨论】:
-
它看起来像编译器错误。就像,如果你用
struct Vector<T>替换class Vector<T>它就可以了。也许它与类中的继承有关。 -
好的,
final class也可以。它肯定会失败,因为类可以被继承并且Self指向 Vector或其任何子类。 -
好的,感谢您的帮助!
-
这应该写成答案。
标签: swift generics operator-overloading