How To Get Absolute Value In Swift

By Eddy Chung

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) // 30

Absolute 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))
// 10

The abs() function also works on Double values:

let negative = -30.2
let absoluteValue = abs(negative)
print(absoluteValue) // 30.2

Using Magnitude Property

You can use the magnitude property to get the absolute value as well. Here is a code example:

let negative = -5
print(negative.magnitude) // 5

This also works on Double values:

let negative2 = -5.5
print(negative2.magnitude) // 5.5
If you liked this post, you'll love my free guide: Secrets To iOS Development. Speed up your learning curve - hundreds of students have already downloaded. Thanks for reading!
Profile Picture of Eddy Chung

Eddy Chung

I am a professional iOS developer in Silicon Valley. I teach iOS development on ZeroToAppStore.com. If you'd like to learn more about me click here or you can contact me at: eddy@zerotoappstore.com

Similar Posts