Library reference

Absolute value

The absolute value tells you how far a number is from zero.

abs

Simple example

Start−3
Result3
main.swift
print(abs(-3))
Output
3
Advertisements

Everyday examples

It is −6 degrees outside. How many degrees below zero is that?

Start−6 → 0
Result6
main.swift
let temperature = -6
print(abs(temperature))
Output
6

The target is 15 points and the score is 12. How far apart are they?

Start12 − 15
Result3
main.swift
let score = 12
let target = 15
print(abs((score - target)))
Output
3

A lift goes from floor 5 to floor 2. How many floors does it travel?

Start5 → 2
Result3
main.swift
let start = 5
let finish = 2
print(abs((finish - start)))
Output
3

Use small signed numbers here. The result is the distance from zero.

Run the example
Terminal
swift main.swift
Official documentation