我是Swift的新手,所以如果我遗漏了一些明显的痛苦的东西,请告诉我。我有一个希望通过值传递以重载+操作符的class。
如果我将左参数lhs定义为foo,代码将无法工作,但是它是不可变的,如果lhs为inout foo,代码将会工作,但是我已经修改了lhs,这显然不是我想要的。
对我的课程做一个简单的分类:
class foo<T: Numeric> {
/* Data */
/* Init Fn */
/* += definition */
static func + (lhs: foo, rhs: foo) -> foo {
do {
try lhs += rhs
return lhs
} catch {
/* Error Handling */
}
}
}我来自C++背景,所以我很惊讶,如果我选择的话,我不能通过值传递对象。在问题What are the basic rules and idioms for operator overloading?之后,在C++中,这个重载方法期望左参数通过值传递,右参数由const &传递,如下所示,但在这里我似乎没有这个选项。
class X {
/* In Swift operators are not defined internally like this */
X& operator+=(const X& rhs) {
// actual addition of rhs to *this
return *this;
}
};
inline X operator+(X lhs, const X& rhs) {
lhs += rhs;
return lhs;
}有没有一种我不知道的方式,或者重载在Swift中是不同的?
任何帮助都将不胜感激。
发布于 2019-02-18 05:56:13
我看不出可变性有什么真正的问题。请注意,对于没有按值传递的类,您不能使用一个运算符来定义另一个运算符。
class Foo<T: Numeric> {
var value: T
init(value: T) {
self.value = value
}
static func + (lhs: Foo, rhs: Foo) -> Foo {
return Foo(value: lhs.value + rhs.value)
}
static func += (lhs: Foo, rhs: Foo) {
lhs.value += rhs.value
}
}
let ten = Foo<Int>(value: 10)
let eighteen = ten + Foo<Int>(value: 8)
eighteen += Foo<Int>(value: 1)https://stackoverflow.com/questions/54737922
复制相似问题