Tuesday, March 10, 2015

How to create custom operators in Swift?

In Swift, you can create your own custom operators in additions to the Swift operators. 

Swift has Unary, Binary and Ternary Operators. You can create the custom operators for Unary and Binary operators. For Unary operators, you can use Prefix and Postfix modifier and for Binary Operator, you can use Infix modifier.

Currently, we cannot write the Custom Ternary operators. Swift has only one Ternary Operator that is Condition operator.
eg- a ? b: c

Following are the modifier which you can use to create the custom operators. 

Prefix- A Unary Operator that is placed before the operand.
eg- b = ++a (++ is operator and a is operand)

Postfix- A Unary Operator that is placed after the operand.
eg- b = a++

Infix- A Binary operator that is placed in between the two operands.
eg- c = a + b

You can create the custom operators that starts with one of the ASCII characters /, =, -, +, !, *, %, <, >, &, |, , or ~, or any of the Unicode characters in the "Math Symbols" character set.

Note-  As mentioned in the Apple documentation, there are some operators which can’t be overloaded nor can be used as Custom Operators. 
The tokens =, ->, //, /*, */, ., the prefix operators <, &, and ?, the infix operator ?, and the postfix operators >, !, and ? are reserved. These tokens can’t be overloaded, nor can they be used as custom operators.

Implementing a Prefix and postfix operator-

As you know that Unary operator operates on single operand. It can be Prefix (++a) if they precede the operand or Postfix (a++) if they follows the operand.

You can implement your own custom unary operators by preceding the operators function with the prefix and postfix modifier.

Let’s declare the +++  prefix operator which can doubles the operand’s value.

prefix operator +++ {}

Now, define the operator functions.

prefix func +++ (number: Double) -> Double {
    return (number + number)
}

let value = +++10 // 20

In the same way, you can create the unary operator with  the postfix modifier.




Implementing an Infix Operator- 

Infix operator is operates on two operators and placed in between the two operands. When you declare the custom Infix operators you can specify the Associativity and Precedence. 

If there are two or more infix operators in the expressions then on the basis of Associativity and Precedence, it can be define which infix operator executes first.

Here, we have define the new custom infix operator +- with left associativity and 140 precedence.

Associativity value can be left, Right and None. By default it is None and the precedence value is 100 if it is not specified. 

infix operator +- { associativity left precedence 140 }

Now, implements the +- operator which returns the tuple value of sum and difference of two operands.

func +- (left: Double, right: Double) -> (Double, Double) {
    return (left + right, left - right)
}

let value = 3 +- 2 // (5, 1)