Swift Operator overloading

Operator overloading is special concept to provide new definition of existing operator without lose its original behavior. This is reliable to provide a special meaning to operator.

Lets an example, We are know about (+) plus operator are use to combine two numeric values or Two string values. Similar we can provide a new meaning to (+) operator which can capable to add two objects. See this example.

class Records{
    
    var x : Int 
    var y : Int
    init(_ x : Int,_ y : Int){
        self.x=x
        self.y=y
    }
    func display(){
        print("X: \(x)  Y: \(y)")
    }
    //Overload + operator
    static func + (lhs : Records,rhs : Records)-> Records{
    
        return Records(lhs.x+rhs.x,lhs.y+rhs.y)
    }
}
let first = Records(3,4)
let second = Records(2,3)
let third = first + second
print("First Records")
first.display()
print("Second Records")
second.display()
print("Third Records")
third.display()

Output

First Records
X: 3  Y: 4
Second Records
X: 2  Y: 3
Third Records
X: 5  Y: 7

That is very similar to define a function only difference are replace the method name by operator. That is a way to provides new properties of inbuilt operator.

Other examples. Suppose we are multiplication of one string variable or String literal into a integer literal. In this situation swift is not allowing to multiply one string to another integers, and compiler are produce error.

let mutiply="A" * 7

print("mutiply: \(mutiply)")
test.swift:1:17: error: binary operator '*' cannot be applied to operands of type 'String' and 'Int'
let mutiply="A" * 7
            ~~~ ^ ~
test.swift:1:17: note: expected an argument list of type '(Int, Int)'
let mutiply="A" * 7
                ^

Because this is logically invalid, But assume that we are need to handle this type of operation which are support to apply multiply operator to string and integers. and resultant is produce on string result which is combination of repeted string value into N given integer.

In this situation we are defined the definition of multiplication operator which are perform this task. See this example.

//Overload * operator
func *(lhs:String,rhs:Int)->String{
    var result:String=""
    var counter:Int=0

    while(counter<rhs){
       result+=lhs
       counter+=1
    }
    return result
}


let overload="A" * 7 //Overload * operator
let simple=16*22
print("overload: \(overload)")
print("simple :  \(simple)")

Output

overload: AAAAAAA
simple :  352

In this example obser that perform the multiplication operation, one is perform of two integers and one is performed by function overloading.

Note that provide the definition of operator is similar to function function.But here few modification are required there name of function are replaced by the operator symbols. And remaining are same as to function definition.

Inside the body we are write a logic which are return the result of string. Note that we can write same logic by normal function definition. But the advantage of operator overloading is we are no need to pass parameter list to defining operator definition. That will automatically call relative to operators (data types).

Test cases of the definition of this operator.

//Overload * operator
func *(lhs:String,rhs:Int)->String{
    var result:String=""
    var counter:Int=0

    while(counter<rhs){
       result+=lhs
       counter+=1
    }
    return result
}


let testOne="A" * 7     //AAAAAAA
let testTwo="A" * -1    //""
let testThree="A" * -0  //""

print("test one: \(testOne)")
print("test two: \(testTwo)")
print("test three: \(testThree)")
test one: AAAAAAA
test two: 
test three: 

Define custom swift operators

Swift Programming are allowing to create custom operator which can be perform some special task using operands. Generally operators are three type infix prefix and postfix. When we are implement custom operator so there is important to define the definition of operator. like operator type, return values , associativity rules and operand types etc.

We can divide implementation of custom operator in three phase. such as declaration, definition and uses.

Declaration: This is a basic declaration of operation that are indicates the behaviour of operator.

Definition: That is actual implementation of operator definition, that are producing the result to using of operator.

Use :That is implementation process for operator.

prefix operator

prefix is work on only one operand. We are implement prefix increment ++ operator in this section.

prefix operator ++
prefix func ++(rhs: inout Int)->Int{

    rhs+=1
    return rhs
}
var a = 10 
let b = ++a 

print(" b : \(b)")//11
print(" a : \(a)")//11

Output

 b : 11
 a : 11

infix operator

Infix means this operator are work on two values. Suppose we are implemented ** operator as calculate power of (a^b).

//Implement ** as power (a ^ b) a and b is integer values
infix operator **
//define the defination and working of **
func **(lhs:Int,rhs:Int)->Int{

    var result=lhs
    if(result==0){
        return 0;
    }
    for _ in 2...rhs{
        result*=lhs
    }
    return result
}
var a = 3**4 //3X3X3X3 =81
var b = 7**5 //7*7*7*7*7 =16807

print(" a : \(a)")//81
print(" b : \(b)")//16807

Output

 a : 81
 b : 16807

postfix operator

Postfix ++ increment operator of other programming language like C, C++ are first used variable value after that variable value are incremented by one. This same process we can implement in swift programming.

postfix operator  ++
postfix func  ++ (rhs: inout Int)->Int{
    let result=rhs
    rhs+=1
    return result
}
var a = 10 
let b = a++

print(" b : \(b)")//10
print(" a : \(a)")//11

Output

 b : 10
 a : 11


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved