In Swift, you can use the exponentiation operator **
to raise a number to a power, which is equivalent to squaring a number by raising it to the power of 2. Here's an example:
main.swift54 chars3 lines
In this example, we declare a constant num
that stores the value 5
. We then use the exponentiation operator **
to raise num
to the power of 2, which results in the value 25. The result is stored in a constant result
.
Alternatively, you could use the pow()
function from the Foundation
module to achieve the same result. Here's an example:
main.swift76 chars5 lines
In this example, we import the Foundation
module, which provides the pow()
function for performing exponentiation. We declare a constant num
that stores the value 5
. We then use the pow()
function to raise num
to the power of 2, producing the value 25. The result is stored in a constant result
.
gistlibby LogSnag