Compound assignment operator

Most built-in operators have a corresponding compound assignment version. Do the same for the exponentiation operator:

infix operator **=

func =(lhs: inout Int, rhs: Int) { lhs = lhs rhs

}

The operator’s name is **= and it is infix, just like the exponentiation operator created earlier. It has no return type and instead uses the inout keyword in front of the type of the operand you are modifying. You’ve already seen inout in action in Chapter 6, “Functions”. The function changes the inout parameter directly because it’s passed by reference.

This is how the operator works:

var number = 2 number **= exponent

Your custom operator is really cool and all, but it only works for Int. Time to make it generic! :]

results matching ""

    No results matching ""