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) ...
Get Cocoa Programming for OS X: The Big Nerd Ranch Guide now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.