Swift - Convert to absolute value Swift - Convert to absolute value swift swift

Swift - Convert to absolute value


The standard abs() function works great here:

let c = -8print(abs(c))// 8


With Swift 5, you may use one of the two following ways in order to convert an integer to its absolute value.


#1. Get absolute value of an Int from magnitude property

Int has a magnitude property. magnitude has the following declaration:

var magnitude: UInt { get }

For any numeric value x, x.magnitude is the absolute value of x.

The following code snippet shows how to use magnitude property in order to get the absolute value on an Int instance:

let value = -5print(value.magnitude) // prints: 5

#2. Get absolute value of an Int from abs(_:) method

Swift has a global numeric function called abs(_:) method. abs(_:) has the following declaration:

func abs<T>(_ x: T) -> T where T : Comparable, T : SignedNumeric

Returns the absolute value of the given number.

The following code snippet shows how to use abs(_:) global function in order to get the absolute value on an Int instance:

let value = -5print(abs(value)) // prints: 5


If you want to force a number to change or keep it positive.
Here is the way:

abs() for intfabs() for doublefabsf() for float