Exponentiation operator

The exponentiation operator is a custom one, so you get to choose its name yourself. It's usually best to stick to the characters /, =, -, +, !, *, %, <, >, &, |, ^ and

?, although many other Unicode characters are allowed. Keep in mind you’ll have to type it often, so the fewer keystrokes, the better. Since exponentiation is repeated multiplication under the hood, it would be nice to choose something which reflects that, so use ** for the operator’s name.

Now for the operator’s type. Swift doesn’t let you declare custom ternary operators, so you are stuck with the prefix, postfix and infix ones. The ** operator works with two operands, so it’s an infix operator.

Here’s what the operator’s signature looks like:

infix operator **

Nothing fancy here: the operator’s name and type bundled into one line of code with the operator keyword. As for the operator’s implementation, it looks like this:

func **(lhs: Int, rhs: Int) -> Int { var result = lhs

for _ in 2...rhs { result *= lhs

}

return result

}

The function takes two arguments of type Int and uses loops, ranges and wildcards to return the first argument raised to the power of the second one; notice the multiplication assignment operator in action.

Note: You use the wildcard pattern to discard the loop’s values; you will learn more about it and other pattern matching techniques in Chapter 21, “Pattern Matching”.

Now test your brand-new operator:

let base = 2 let exponent = 2

let result = base ** exponent

results matching ""

    No results matching ""