I was just going through the Swift document and I found that Swift allow to overload the operator just like as C++ Language. Objective-C doesn’t allow to overload the operator.
As swift document we can also say “Operator Functions”.
Let’s Overload ^ (XOR Operator) to make Power of the value
Function Prototype :
Declare function prototype with left hand side value and right and side value.
1 2 |
func ^(lhs: Int, rhs: Int) -> Int { } |
Operations in the function :
To make the power of the value we have to apply following operations
1 2 3 4 5 6 7 8 9 10 11 12 |
func ^(lhs: Int, rhs: Int) -> Int { if(rhs == 0) { return 1 } else { var result = lhs for _ in 1 ..< rhs { result *= lhs } return result } } |
Let’s try to use with the operator :
1 2 3 |
let a = 2^2 //4 let b = 2^4 //16 let c = 3^3 //27 |
Happy Coding 🙂