定义+时自动定义+ =?

时间:2017-02-26 04:01:54

标签: swift swift3

我有一个为其定义了自定义+的类型。我想知道Swift是否可以自动为+=编写定义,即a += b - > a = a+b。理想情况下,我不必为我写的每个运算符编写相应的赋值运算符。

示例代码:

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

1 个答案:

答案 0 :(得分:4)

通常,您在定义+=时必须定义+

您可以创建一个Summable协议来声明++=,但是由于添加了任意类型,您仍然需要定义+函数没有具体的意义。这是一个例子:

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
}