What is the cos() function in Swift?

Overview

In Swift, the cos() function returns the cosine of a number.

The mathematical representation of the cos() function is shown below:

Mathematical representation of the cosine function

Note: We need to import Foundation in our code to use the cos() function. We can import it using import Foundation.

Syntax


cos(number)
//number can be real, float, or double.

Parameters

This function requires a number that represents an angle in radians as a parameter.

To convert degrees to radians, use the following formula:


radians = degrees * ( pi / 180 )

Return value

This function returns the cosine of the number that is sent as a parameter. The return value will be between -1 and 1.

Example

import Swift
import Foundation
//positive number in radians
print("The value of cos(2.3) :", cos(2.3));
// negative number in radians
print("The value of cos(-2.3) :", cos(-2.3));
//converting the degrees angle into radians and then applying cos()
// degrees = 180.0
// PI = 3.14159265
print("The value of cos(180.0 * (PI / 180.0)) :", cos(180.0 * (Double.pi / 180.0)));

Explanation

  • Line 2: We add the Foundation header required for the cos() function.
  • Line 5: We use cos() to calculate the cosine of the positive number in radians.
  • Line 8: We use cos() to calculate the cosine of the negative number in radians.
  • Line 13: We use cos() to convert the angle in degrees to radians and calculate its cosine.

    Free Resources