0
0
Swiftprogramming~5 mins

Operator overloading concept in Swift

Choose your learning style9 modes available
Introduction

Operator overloading lets you change how operators like + or - work with your own types. It makes your code easier to read and use.

You want to add two custom objects like points or vectors using +.
You want to compare two objects with == or != in a natural way.
You want to multiply or divide your own data types with * or /.
You want to use operators to combine or modify your custom types simply.
Syntax
Swift
static func operatorName(lhs: YourType, rhs: YourType) -> YourType {
    // code to combine lhs and rhs
}

Use static func inside your type to define how the operator works.

The operator function usually takes two parameters: left and right side values.

Examples
This example adds two points by adding their x and y values.
Swift
struct Point {
    var x: Int
    var y: Int

    static func + (lhs: Point, rhs: Point) -> Point {
        return Point(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
    }
}
This example multiplies a vector by an integer.
Swift
struct Vector {
    var value: Int

    static func * (lhs: Vector, rhs: Int) -> Vector {
        return Vector(value: lhs.value * rhs)
    }
}
Sample Program

This program creates two points and adds them using the overloaded + operator. It then prints the result.

Swift
struct Point {
    var x: Int
    var y: Int

    static func + (lhs: Point, rhs: Point) -> Point {
        return Point(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
    }
}

let p1 = Point(x: 3, y: 4)
let p2 = Point(x: 5, y: 7)
let p3 = p1 + p2
print("p3 is at (\(p3.x), \(p3.y))")
OutputSuccess
Important Notes

Only certain operators can be overloaded in Swift.

Make sure your operator overloading keeps the meaning clear to avoid confusing code.

Summary

Operator overloading lets you define how operators work with your own types.

It makes your code cleaner and easier to understand.

Use static func inside your type to overload operators.