# Swift-技巧（十一）重写运算符

Swift 中有经常用到加、减、乘、除的操作，在代码中编写这些操作，实现功能中需要的基础计算。比如下面代码中实现的加法操作。

``````let a = 1
let b = 2
let c = a + b
// c = 3
``````

``````let point1 = CGPoint(x: 1, y: 2)
let point2 = CGPoint(x: 3, y: 4)

// point1 加 point2
let x = point1.x + point2.x
let y = point1.y + point2.y
let result = CGPoint(x: x, y: y)
``````

``````func addFunc(with point1: CGPoint, point2: CGPoint) -> CGPoint {

let x = point1.x + point2.x
let y = point1.y + point2.y
return CGPoint(x: x, y: y)
}
``````

``````let result = addFunc(with point1, point2)
``````

Swift 中恰好有重写运算符的方式，直接在 `struct` 或者 `class` 上使用加、减、乘、除这些操作。那么如何重写运算符呢

``````static func + (_ point1: CGPoint, _ point2: CGPoint) -> CGPoint {
return CGPoint(x: point1.x + point2.x, y: point1.y + point2.y)
}
``````

``````let result = point1 + point2
``````

### 进阶

``````extension CGPoint {
static func + (_ point1: CGPoint, _ point2: CGPoint) -> CGPoint {
return CGPoint(x: point1.x + point2.x, y: point1.y + point2.y)
}
}
``````

``````static func += (point1: inout CGPoint, _ point2: CGPoint) {
point1.x += point2.x
point1.y += point2.y
}
``````