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:
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 numberprint ("The value of abs(10) : ",abs(10));//zeroprint ("The value of abs(0) : ",abs(0));//negative numberprint ("The value of abs(-10) : ",abs(-10));
Explanation
-
Line 4: We calculate the absolute value of the positive number
10usingabs(). -
Line 7: We calculate the absolute value of
0usingabs(). -
Line 10: We calculate the absolute value of the negative number
-10usingabs().