Operator functions or operator overloading is a way to allow structures and classes to provide their own implementation of existing operators. Imagine that you have two points of type CGPoint
and you want to get the sum of both points. The solution will be to create another point and set its x, y with sum of x's and y's of points. It's simple right? But what if we override the +
operator that accepts the summation of two points. Still not clear? Check this example:
func +(lhs:CGPoint, rhs:CGPoint) -> CGPoint { return CGPoint(x: lhs.x + rhs.x, y: lhs.y + rhs.y) } let p1 = CGPoint(x: 1, y: 4) let p2 = CGPoint(x: 5, y: 2) let p3 = p1 + p2 //{x 6 y 6}
In the example, we wrote the function and its name is just the +
operator. It takes two parameters, lhs
and rhs
, which means the left-hand side and right-hand side of the equation is a summation. The function returns a point, which is the sum of the two points. Then, in the code, we wrote p1 + p2
. This code will call...