What is abs() in Swift?

Overview

The abs() function returns the absolute value of a number. The mathematical representation of abs function is as follows:

abs(X)=Xabs(X) = \mid X \mid

Syntax

abs(num)

num is the number whose absolute value is required.

Parameter

The abs() function takes a number as a parameter.

Return value

The abs() function returns the absolute value of a number passed as a parameter.

Example

The following code shows the use of the abs() function in Swift:

import Swift
//positive number
print ("The value of abs(10) : ",abs(10));
//zero
print ("The value of abs(0) : ",abs(0));
//negative number
print ("The value of abs(-10) : ",abs(-10));

Explanation

  • Line 4: We calculate the absolute value of the positive number 10 using abs().

  • Line 7: We calculate the absolute value of 0 using abs().

  • Line 10: We calculate the absolute value of the negative number -10 using abs().

Free Resources