Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Convert to absolute value

Tags:

ios

swift

iphone

People also ask

What does abs do in Swift?

The Anti-Lock braking system has two key functions. Foremost, is to stop the wheels from locking up when immediate brakes are applied and secondly to prevent the car from skidding on slippery roads. Furthermore, Swift's ABS has been accompanied by electronic brake force distribution system and brake assist.

What is UInt in Swift?

Swift also provides an unsigned integer type, UInt , which has the same size as the current platform's native word size: On a 32-bit platform, UInt is the same size as UInt32 . On a 64-bit platform, UInt is the same size as UInt64 .

Why is absolute value important?

1 Answer. Because it is a convenient way to make sure that a quantity is nonnegative; for example, you can define the distance between two real numbers a and b as |a−b| .

How do you know if a number is negative in Swift?

Try using value < 0. This will check if the value is less than 0.


The standard abs() function works great here:

let c = -8
print(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 = -5
print(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 = -5
print(abs(value)) // prints: 5

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

abs() for int
fabs() for double
fabsf() for float

If you want to get absolute value from a double or Int, use fabs func:

var c = -12.09
print(fabs(c)) // 12.09
c = -6
print(fabs(c)) // 6