Overload the `+` Addition Operator for Custom Swift Types
Written by Team Kodeco
When working with custom types in Swift, you may want to overload the +
operator to perform custom logic when adding two instances of that type together.
Here’s an example of how you might overload the +
operator for a custom Point
class:
class Point {
var x: Int
var y: Int
init(x: Int, y: Int) {
self.x = x
self.y = y
}
}
extension Point {
static func +(lhs: Point, rhs: Point) -> Point {
return Point(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
}
}
In this example, you define a Point
class with x
and y
properties. You then define an extension on the Point
class and overload the +
operator by defining a static function called +
that takes two Point
parameters and returns a new Point
instance with the x
and y
properties added together.
Now you can use the +
operator to add two Point
instances together:
let point1 = Point(x: 1, y: 2)
let point2 = Point(x: 3, y: 4)
let point3 = point1 + point2
print(point3.x) // 4
print(point3.y) // 6