April 2015
Intermediate to advanced
556 pages
17h 47m
English
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: ...Read now
Unlock full access