What is the pow() function in Swift?

Overview

The pow() function calculates the value of a numberbase raised to the power of another numberexponent.

The figure below shows the mathematical representation of the pow() function:

Figure 1: Mathematical representation of pow() function

Note: We need to import Foundation in our code to use the pow() function. We can import it like this: import Foundation.

Syntax

Let's view the syntax of the function:

pow(baseNumber, exponent)
Function syntax

Parameters

The pow() function requires two parameters:

  • A base number.
  • An exponent number.

Return value

The pow() returns the value of the base number raised to the exponent number.

Code example

The code below shows the use of the pow() function in Swift:

import Swift
import Foundation
//positive: baseNumber positive: exponent
print ("The value of pow(2.0,3.0) : ",pow(2.0,3.0));
//positive: baseNumber negative: exponent
print ("The value of pow(0.25,-2.0) : ",pow(0.25,-2.0));
//negative: baseNumber positive: exponent
print ("The value of pow(-10.0,2.0) : ",pow(-10.0,2.0));
//negative: baseNumber negative: exponent
print ("The value of pow(-0.5,-1.0) : ",pow(-0.5,-1.0));

Code explanation

  • Line 2: We add the Foundation header required for the pow() function.
  • Line 5: We calculate the positive base number raised to the positive exponent using pow().
  • Line 8: We calculate the positive base number raised to the negative exponent using pow().
  • Line 11: We calculate the negative base number raised to the positive exponent using pow().
  • Line 14: We calculate the negative base number raised to the negative exponent using pow().

Free Resources