Home > Articles > Programming > General Programming/Other Languages

  • Print
  • + Share This
This chapter is from the book

Operator Overloading

By overloading operators you can make your own types work with common (and even uncommon) operators. This ability falls deep beyond the “with great power comes great responsibility” line. However, vectors are a natural and respectable application for this technique.

To define an operator overload you simply add a function that takes the appropriate types. To start with, instead of calling vectorByAddingVector(_:), it would be nice to use the + operator. Overload + and * for adding and scaling vectors, respectively.

struct Vector {

func +(left: Vector, right: Vector) -> Vector {
    return left.vectorByAddingVector(right)
func *(left: Vector, right: Double) -> Vector {
    return Vector(x: left.x * right , y: left.y * right)

Now you can very succinctly manipulate vectors:

let twoGs = gravity.vectorByAddingVector(gravity)
let twoGs = gravity + gravity
let twoGsAlso = gravity * 2.0

Note that the order of types for binary operators like * and + is important. In order to write 2.0 * gravity you will need to implement another operator overload function:

func *(left: Double, right: Vector) -> Vector {
    return right * left
  • + Share This
  • 🔖 Save To Your Account