I'm new to Swift so please let me know if I've missed something painful obvious. I have a class
that I want to pass by value to overload the +
operator.
The code won't work if I define the left argument lhs
as foo
but then it is immutable, and will work if lhs
is inout foo
, but then I have modified lhs
which I clearly do not want.
A quick breakdown of my class:
class foo<T: Numeric> {
/* Data */
/* Init Fn */
/* += definition */
static func + (lhs: foo, rhs: foo) -> foo {
do {
try lhs += rhs
return lhs
} catch {
/* Error Handling */
}
}
}
I come from a C++ background, so I am surprised that I am unable to pass the object by value if I choose. Following the question What are the basic rules and idioms for operator overloading?, in C++ this overloading method would expect the left argument to be passed by value and the right argument to be passed by const &
as shown below, but here I don't seem to have that option.
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;
}
Is there a way that I don't know about, or is overloading done differently in Swift?
Any help would be greatly appreciated.