O'Reilly logo

Application Development with Swift by Hossam Ghareeb

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 functions

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

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