我有一個爲其定義的自定義+
的類型。我想知道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
你可以發佈重載操作符方法的代碼嗎? – ZeMoon
@ZeMoon我添加了示例代碼 – BallpointBen