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.

s​t​r​u​c​t​ ​V​e​c​t​o​r​ ​{​
 ​ ​ ​ ​.​.​.​
}​

f​u​n​c​ ​+​(​l​e​f​t​:​ ​V​e​c​t​o​r​,​ ​r​i​g​h​t​:​ ​V​e​c​t​o​r​)​ ​-​>​ ​V​e​c​t​o​r​ ​{​
 ​ ​ ​ ​r​e​t​u​r​n​ ​l​e​f​t​.​v​e​c​t​o​r​B​y​A​d​d​i​n​g​V​e​c​t​o​r​(​r​i​g​h​t​) ...

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.