Search Your Question

What is Operator overloading?

Ans : 
Operator overloading is the practice of adding new operators and modifying existing ones to do different things. Operators are those little symbols like +*, and /, and Swift uses them in a variety of ways depending on context – a string plus another string equals a combined string, for example, whereas an integer plus another integer equals a summed integer.
To create a new operator, try adding this to a playground:
infix operator **
That’s the exponentiation operator, designed to raise one number to the power of another. Normally we’d use the pow() function for that job, but with operator overloading we can make ** work instead.
Now you need to tell Swift what to do when it sees that operator. For example, when we write something like 2 ** 4 what does that mean?
Syntax of making operator : 
func **(lhs: Double, rhs: Double) -> Double {
    return pow(lhs, rhs)
Use : 
let result = 2 ** 4
We can specify associativity and a precedence group also but it is very deep level.
If you have any comment, question, or recommendation, feel free to post them in the comment section below!

No comments:

Post a Comment