Swift Tutorial Swift References

Swift - abs() Function



The Swift abs() function returns the absolute value (positive value) of the specified number. For example - absolute value of x will be |x|.

Syntax

public func abs(_ x: CGFloat) -> CGFloat
public func abs(_ x: Float) -> Float
public func abs(_ x: Float80) -> Float80
public func abs(_ __x: Double) -> Double
public func abs(_ x: Int) -> Int

Parameters

x Specify a number whose absolute value need to be determined.

Return Value

Returns the absolute value (positive value) of the argument.

Example:

In the example below, abs() function returns the absolute value (positive value) of the specified number.

print("abs(-2.0) = \(abs(-2.0))")
print("abs(-1.0) = \(abs(-1.0))")
print("abs(0.0) = \(abs(0.0))")
print("abs(1.0) = \(abs(1.0))")
print("abs(2.0) = \(abs(2.0))")

The output of the above code will be:

abs(-2.0) = 2.0
abs(-1.0) = 1.0
abs(0.0) = 0.0
abs(1.0) = 1.0
abs(2.0) = 2.0

❮ Swift Math Functions

5