To get the absolute value in Swift, you can use the abs() function. Here is a code example:
let negativeNumber = -30
let absoluteValue = abs(negativeNumber)
print(absoluteValue) // 30Absolute value is useful when you only care about the magnitude of a number, not whether if it is positive or negative.
If you call abs() on a positive number, it will return the same value:
print(abs(10))
// 10The abs() function also works on Double values:
let negative = -30.2
let absoluteValue = abs(negative)
print(absoluteValue) // 30.2You can use the magnitude property to get the absolute value as well. Here is a code example:
let negative = -5
print(negative.magnitude) // 5This also works on Double values:
let negative2 = -5.5
print(negative2.magnitude) // 5.5
The Complete iOS App Development Bootcamp
Disclosure: This website may contain affiliate links, meaning when you click the links and make a purchase, we receive a commission.