运算符函数
struct Vector2D { var x = 0.0,y = 0.0 } func + (left: Vector2D,right: Vector2D) -> Vector2D { return Vector2D(x: left.x + right.x,y: left.y + right.y) } let vector = Vector2D(x: 3.0,y: 1.0) let anotherVector = Vector2D(x: 2.0,y: 4.0) let combinedVector = vector + anotherVector // combinedVector 是一个新的Vector2D,值为 (5.0,5.0)
前置或后置运算符
函数前标注 prefix或postfix
prefix func - (vector: Vector2D) -> Vector2D { return Vector2D(x: -vector.x,y: -vector.y) } let positive = Vector2D(x: 3.0,y: 4.0) let negative = -positive // negative 为 (-3.0,-4.0) let alsoPositive = -negative // alsoPositive 为 (3.0,4.0)
组合赋值表达式
func += (inout left: Vector2D,right: Vector2D) { left = left + right } var original = Vector2D(x: 1.0,y: 2.0) let vectorToAdd = Vector2D(x: 3.0,y: 4.0) original += vectorToAdd // original 现在为 (4.0,6.0)
prefix func ++ (inout vector: Vector2D) -> Vector2D { vector += Vector2D(x: 1.0,y: 1.0) return vector } var toIncrement = Vector2D(x: 3.0,y: 4.0) let afterIncrement = ++toIncrement // toIncrement 现在是 (4.0,5.0) // afterIncrement 现在也是 (4.0,5.0)
比较运算符
func == (left: Vector2D,right: Vector2D) -> Bool { return (left.x == right.x) && (left.y == right.y) } func != (left: Vector2D,right: Vector2D) -> Bool { return !(left == right) } let twoThree = Vector2D(x: 2.0,y: 3.0) let anotherTwoThree = Vector2D(x: 2.0,y: 3.0) if twoThree == anotherTwoThree { print("这两个向量是相等的.") }