O'Reilly logo

Cocoa Programming for OS X: The Big Nerd Ranch Guide by Aaron Hillegass, Adam Preble, Nate Chandler

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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​) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required