Operator overloading in Swift

Operator overloading is a method through which we implement operators in user-defined types with a unique logic dependent on the kinds of arguments given in a programming language. Operators are symbols like +, /, and *.

Swift, a programming language, employs these operators in various ways. For instance, a string plus another string results in a combined string. Similarly, an integer plus another integer results in a summed integer.

Operator overloading

With custom precedence and associativity values, Swift allows you to define your infix, prefix, postfix, and assignment operators. These operators are just like any predefined operators in your code. Existing operator types can be expanded to enable your custom operators.

The operator used between two numbers is called the infix operator. For example, in operation 4+5, + is the infix operator. To create a new variable, we’ll add the following line to our playground:

Error: Code Block Widget Crashed, Please Contact Support

Exponentiation is a mathematical operation used to raise one integer to the power of another. Instead of using the pow() function as we would normally do. In the above line, we’ve made ++ work by using operator overloading.

Next, we’ll tell Swift what to do when it comes across this operator. What does it mean, for instance, when we write something like 2 ++ 4?

Code example

Let’s look at an example of operator overloading in Swift:

import Foundation
infix operator ++
func ++(num1: Float, num2: Float) -> Float {
return pow(num1, num2)
}
let output = 4 ++ 5
print (output)
Implementing operator overloading
  • Line 2: We declare the ++ operator to be overloaded.

  • Line 3: We take two float parameters, num1 and num2, and return a float number. In this overloaded implementation, we calculate num1, raised to the power of num2 using the pow() function.

  • Line 6: 4 ++ 5 calls the overloaded implementation of the ++ operator and saves the result to output variable. In this case, the expression 4 ++ 5 is equivalent to pow(4, 5), which is 1024.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved