take the absolute value of a number in swift

To take the absolute value of a number in Swift, you can use the abs function. This function works with integers, floating-point numbers and other numeric types in Swift.

Here's an example code snippet:

main.swift
let num = -10
let absNum = abs(num)
print(absNum) // Output: 10
64 chars
4 lines

In this example, we declare a variable num with a value of -10. We then use the abs function to get the absolute value of num and assign it to a new variable absNum. Finally, we print the value of absNum which is 10.

You can also use abs with floating-point numbers:

main.swift
let num = -10.5
let absNum = abs(num)
print(absNum) // Output: 10.5
68 chars
4 lines

In this example, we declare a variable num with a value of -10.5 which is a floating-point number. We then use the abs function to get the absolute value of num and assign it to a new variable absNum. Finally, we print the value of absNum which is 10.5.

gistlibby LogSnag