Custom Operators allow you to specify custom operations that should be performed on
● two Variables (Infix Custom Operators: john + bob)
● single Variable (Prefix & Postfix Custom Operators: +++age, age+++)
First we need to declare the operator as a global variable before we can write its implementation.
Highlighted parts are added so that operator would also return the value (allowing us to store it into another variable).
Without them Prefix & Postfix Operators would only change the value of the Variable on which they were applied.
And in the case of Infix Operators there would be also no return Value.
In this example we define "+" operator that adds score Properties of two Players structs.
Infix Operator
//DECLARE OPERATOR.
infix operator +
//IMPLEMENT OPERATOR.
func + (left:Player, right:Player) -> (Int) {
return left.score + right.score
}
//DECLARE STRUCT.
struct Player {
var name : String
var score : Int
}
//USE OPERATOR.
var john = Player(name: "John", score: 5)
var bob = Player(name: "Bob" , score: 2)
var totalScore = john + bob //7 Custom Operation. Add scores.
//DISPLAY RESULT.
print(totalScore)