What is the sqrt() function in Swift?

The sqrt() function in Swift returns the square root of a non-negative number.

The figure below shows the mathematical representation of the sqrt() function.

Figure 1: Mathematical representation of the sqrt() function

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

Syntax


sqrt(number)

Parameter

sqrt() requires a non-negative number as a parameter.

Return value

sqrt() returns the square root of the number sent as a parameter.

Example

The code below shows the sqrt() function in Swift.

import Swift
import Foundation
//Perfect square root
print ("The value of sqrt(4.0) : ", sqrt(4.0));
print ("The value of sqrt(0.0) : ",sqrt(0.0));
print ("The value of sqrt(25.0) : ",sqrt(25.0));
//Non-perfect square root
print ("The value of sqrt(4.4) : ",sqrt(4.4));
//Exceptional outputs
print ("The value of sqrt(-4.5) : ",sqrt(-4.5));

Explanation

  • Line 2: We add the Foundation header required for sqrt() function.
  • Lines 4 to 8: We calculate the square root value of perfect square numbers 4, 0, and 25 using sqrt().
  • Line 11: We calculate the square root value of the non-perfect square number 4.4 using sqrt().
  • Line 14: We calculate the square root value of exceptional numbers < 0 using sqrt().

Free Resources