Swift – Operator Overloading
Operator Overloading in Swift
Operator overloading is a powerful technique in Swift programming. Operator overloading allows us to change the working of the existing operators like +, -, /, *, %, etc. with the customized code.
It makes code more expressive and readable. To overload an operator, we have to define the behaviour of that operator using the “static func” keyword.
Syntax
Following is the syntax for operator overloading −
static func operatorName() { // body }
Example 1
Swift program to overload + operator to calculate the sum of two complex numbers.
import Foundation struct ComplexNumber { var real: Double var imag: Double // Overloading + operator to add two complex numbers static func+(left: ComplexNumber, right: ComplexNumber) -> ComplexNumber { return ComplexNumber(real: left.real + right.real, imag: left.imag + right.imag) } } let complexNumber1 = ComplexNumber(real: 2.1, imag: 2.0) let complexNumber2 = ComplexNumber(real: 6.1, imag: 9.0) // Calling + operator to add two complex numbers let sumOfComplexNumbers = complexNumber1 + complexNumber2 print(sumOfComplexNumbers)
Output
ComplexNumber(real: 8.2, imag: 11.0)
Example 2
Swift program to overload custom prefix operator.
import Foundation struct Car { var price: Double // Overloading the custom prefix operator "++" to increase the price of car static prefix func ++ (carPrice: inout Car) { carPrice.price += 500000.0 } } var currentPrice = Car(price: 2500000.0) // Calling the custom ++ operator to increase the car price ++currentPrice print("Updated car price is", currentPrice.price)
Output
Updated car price is 2500000.0
Limitation of Operator Overloading in Swift
The following are the limitations of operator overloading −
- In Swift, you can overload limited operators like arithmetic and customized operators.
- While overloading operators, you are not allowed to change the precedence or associativity of the operators.
- Swift does not support short-circuiting behaviour for overloading logical operators.
- Do not overuse operator overloading because it makes your code difficult to read and understand.
Difference Between Operator Function and Normal Functions
The following are the major differences between the operator functions and normal functions −
Operator Function | Normal Function |
---|---|
They are define using “static func” keyword and a custom operator symbol. | They are defined using “func” keyword and the function name. |
They are used to customize the behaviours of operators. | They are used to complete general purpose tasks. |
They are called implicitly when using operator with custom types. | They are called explicitly with the help of function name. |
They can be defined in index, prefix or postfix form. | They can only defined in infix form. |
”;