代码:
struct Vector2D { var x = 0.0, y = 0.0 } // vector1 + vector2 func + (left: Vector2D, right: Vector2D) -> Vector2D { return Vector2D(x: left.x + right.x, y: left.y + right.y) } // vector1 - vector2 func - (left: Vector2D, right: Vector2D) -> Vector2D { return Vector2D(x: left.x - right.x, y: left.y - right.y) } // -vector prefix func - (vector: Vector2D) -> Vector2D { return Vector2D(x: -vector.x, y: -vector.y) } // vector1 += vector2 func += (inout left: Vector2D, right: Vector2D) { left = left + right } // vector1 -= vector2 func -= (inout left: Vector2D, right: Vector2D) { left = left - right } // ++vector1 prefix func ++ (inout v: Vector2D) -> Vector2D { v += Vector2D(x: 1, y: 1) return v } // vector1++ postfix func ++ (inout v: Vector2D) -> Vector2D { v += Vector2D(x: 1, y: 1) return v } // --vector prefix func -- (inout v: Vector2D) -> Vector2D { v += Vector2D(x: 1, y: 1) return v } // vector-- postfix func -- (inout v: Vector2D) -> Vector2D { v += Vector2D(x: 1, y: 1) return v } // vector1 == vector2 func == (left: Vector2D, right: Vector2D) -> Bool { return (left.x == right.x) && (left.y == right.y) } // vector1 != vector2 func != (left: Vector2D, right: Vector2D) -> Bool { return !(left == right) } // +++vector prefix operator +++ {} prefix func +++ (inout vector: Vector2D) -> Vector2D { vector += vector return vector } // vector+++ postfix operator +++ {} postfix func +++ (inout vector: Vector2D) -> Vector2D { vector += vector return vector } // vector1 +- vector2 infix operator +- { associativity left precedence 140 } func +- (left: Vector2D, right: Vector2D) -> Vector2D { return Vector2D(x: left.x + right.x, y: left.y - right.y) } // vector1 -+ vector2 infix operator -+ { associativity left precedence 140 } func -+ (left: Vector2D, right: Vector2D) -> Vector2D { return Vector2D(x: left.x - right.x, y: left.y + right.y) }