I have a type that has a custom + defined for it. I was wondering if it was possible for Swift to automatically write a definition for +=, namely a += b --> a = a+b. Ideally I would not have to write the corresponding assignment operator for each operator I write.
Sample code:
class A {
var value: Int
init(_ value: Int) {
self.value = value
}
static func +(lhs: A, rhs: A) -> A {
return A(lhs.value + rhs.value)
}
}
var a = A(42)
let b = A(10)
// OK
let c = a + b
// error: binary operator '+=' cannot be applied to two 'A' operands
// Ideally, this would work out of the box by turning it into a = a+b
a += b
Usually you have to define += when you define +.
You could create a Summable protocol that declares both + and +=, but you'll still have to define the + function since addition of arbitrary types has no concrete meaning. Here's an example:
protocol Summable {
static func +(lhs: Self, rhs: Self) -> Self
static func +=(lhs: inout Self, rhs: Self)
}
extension Summable {
static func +=(lhs: inout Self, rhs: Self) { lhs = lhs + rhs }
}
struct S: Summable { }
func +(lhs: S, rhs: S) -> S {
// return whatever it means to add a type of S to S
return S()
}
func f() {
let s0 = S()
let s1 = S()
let _ = s0 + s1
var s3 = S()
s3 += S() // you get this "for free" because S is Summable
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With