Custom Operator in Swift

Level 5637 keystrokes

The code overloads + for Vector2D, declares a prefix operator +++ that doubles a vector in place, and an infix operator ** that scales it. Because +++v1 appears twice in the last line, v1 is doubled twice, so it prints Doubled: (6.0, 16.0).

Swift code

1struct Vector2D {
2 var x: Double
3 var y: Double
4}
5
// Overloads the existing + operator for Vector2D
6func +(left: Vector2D, right: Vector2D) -> Vector2D {
7 return Vector2D(x: left.x + right.x, y: left.y + right.y)
8}
9
// A new operator must be declared before it is implemented
10prefix operator +++
// inout: doubles the vector in place and returns the new value
11prefix func +++(vector: inout Vector2D) -> Vector2D {
12 vector = vector + vector
13 return vector
14}
15
// Infix operator with the same precedence as *
16infix operator **: MultiplicationPrecedence
// Multiplies both components by a scalar
17func **(left: Vector2D, right: Double) -> Vector2D {
18 return Vector2D(x: left.x * right, y: left.y * right)
19}
20
// var because +++ modifies v1
21var v1 = Vector2D(x: 3, y: 4)
22let v2 = Vector2D(x: 1, y: 2)
// (3 + 1, 4 + 2): prints Sum: (4.0, 6.0)
23print("Sum: (\((v1 + v2).x), \((v1 + v2).y))")
// ** does not change v1: prints Scaled: (6.0, 8.0)
24print("Scaled: (\((v1 ** 2).x), \((v1 ** 2).y))")
// Each +++ doubles v1 again: x after (6, 8), y after (12, 16); prints Doubled: (6.0, 16.0)
25print("Doubled: (\((+++v1).x), \((+++v1).y))")

Output

Sum: (4.0, 6.0)
Scaled: (6.0, 8.0)
Doubled: (6.0, 16.0)
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Swift code and how often they appear.

  • (× 25
  • )× 25
  • :× 19
  • +× 18
  • .× 12
  • *× 10
  • ,× 9
  • "× 6
  • \× 6
  • {× 4

More Swift examples at level 5

← Swift typing practice