← All languages
Swift function of the day
Random

abs

Return the absolute value of a number.

Description

The abs function returns the absolute value of the given number. It works with any type that conforms to the Comparable and SignedNumeric protocols, including Int, Double, and Float.

If the argument is not negative, the result is the same as the argument. If the argument is negative, the result is the negation of the argument.

Note that for signed integer types, the absolute value of the minimum value (e.g., Int.min) cannot be represented and will cause a runtime overflow error.

Arguments

NameDescriptionOptional
x A signed numeric value. No

Example

let positive = abs(-42)
print(positive)  // 42
let pi = abs(-3.14)  // 3.14

Reference