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.swift64 chars4 linesIn 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.swift68 chars4 linesIn 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