Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically have += defined when defining +?

Tags:

swift

swift3

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
like image 964
BallpointBen Avatar asked Mar 23 '26 20:03

BallpointBen


1 Answers

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
}
like image 76
par Avatar answered Mar 26 '26 10:03

par



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!