Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 146 ยท Getting Started

Working with Numbers

Master Swift arithmetic - integer division, overflow traps and &+, rounding, Foundation math, Decimal for exact money, bit operations and number formatting.

Numbers are the first thing most programs touch, and Swift handles them with a few firm opinions: arithmetic that would give a wrong answer is an error, conversions are explicit and the standard library gives you precise tools when you want a different behavior. This lesson covers everyday arithmetic, what happens at the edges (overflow and division by zero), rounding, the math functions in Foundation, exact decimal numbers and how to turn numbers into text.

Arithmetic basics

The operators are +, -, *, / and %. Integer division discards the fraction, and the remainder operator follows the sign of the left operand.

Swift Integer and floating-point arithmetic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

/ on two integers is integer division. If you want a fraction, at least one side must be a Double: 7.0 / 2 or Double(a) / Double(b). The % operator exists only for integers; for floating-point values use truncatingRemainder(dividingBy:). To test divisibility, prefer isMultiple(of:), which reads better than n % 3 == 0, and handles negative numbers correctly: 10.isMultiple(of: 3) is false.

Compound assignment operators (+=, -=, *=, /=, %=) update a variable in place. Swift has no ++ or --; write count += 1.

Overflow: the default is to stop

Fixed-size integers hold a limited range. What should UInt8 250 plus 10 be? 260 does not fit in 0...255. Many languages wrap around silently to 4. Swift's ordinary + treats the overflow as a bug and traps. If the compiler can see the problem at compile time, it refuses to build:

Swift A literal that does not fit (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The message is error: integer literal '200' overflows when stored into 'Int8'. When the values are only known at run time, the check happens when the program runs:

Swift Overflow at run time (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The loop runs five times safely (251 to 255), and the sixth += 1 traps. Our runner compiles with optimizations, so the run ends with an illegal-instruction signal (SIGILL) and a backtrace instead of a friendly message; in a debug build you would see a fatal error naming the overflow. Either way, the program stops before it can use a wrong value.

The overflow operators

Sometimes wrap-around is exactly what you want: hash functions, checksums, counters that cycle. For those, Swift offers explicit operators that start with &: &+, &-, &*. And there are methods that tell you whether overflow happened:

Swift Wrapping and reporting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

&+ is explicit: anybody reading it knows wrap-around is intended. addingReportingOverflow returns a tuple with the wrapped value and a flag. For converting between integer types, Int8(clamping:) caps the value to the nearest representable one (127), while Int8(truncatingIfNeeded:) keeps only the low bits (300 becomes 44). The plain Int8(300) would trap.

With 64-bit Int you will rarely overflow by accident, since the maximum is above nine quintillion. Be careful with Int32, UInt8, factorials, Fibonacci numbers and anything that multiplies large values.

Division by zero

Integer division by zero is a trap, just like overflow. Floating-point division by zero follows the IEEE 754 standard and produces infinity or NaN.

Swift Zero denominators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Always guard integer divisors. Remove the if and the program would stop at 100 / 0. For Double, 1.0 / 0.0 prints inf, and 0.0 / 0.0 is NaN, which compares unequal to everything, so check it with isNaN or isFinite.

Conversions

Converting between numeric types always uses an initializer, for example Double(count) or Int(price):

  • Int(3.9) is 3 and Int(-3.9) is -3 (truncation toward zero).
  • Int(exactly: 3.5) returns nil instead of truncating; Int(exactly: 3.0) returns Optional(3).
  • Int("42") parses text and returns an optional.
  • Going from Int to Double can lose precision above 2^53: Float(16_777_217) is 16777216.0.

Rounding

Double has a rounded() method, and a rounding-rule parameter for the variations. The default is "schoolbook" rounding (halves away from zero).

Swift Rounding rules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

.up always goes toward positive infinity, .down toward negative infinity, .towardZero truncates and .toNearestOrEven ("banker's rounding") sends exact halves to the even neighbor, which avoids a statistical bias in long sums. The scale-round-unscale trick works for display purposes, but remember the result is still a binary Double. To show two decimals, format the number (below) rather than rounding it.

Math functions from Foundation

The operators and basic methods are in the standard library. Powers, roots, logarithms and trigonometry come from Foundation:

Swift Foundation math

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

pow takes Doubles (or Decimals), so integer powers need a conversion: Int(pow(Double(2), 10)), though a loop or the bit shift 1 << 10 is safer for exact integer results. The result of cbrt(27.0) came out as 3.0000000000000004 when we tried it on this platform, which is another reason not to compare floating-point numbers with ==. abs, min and max are in the standard library.

Exact decimals with Decimal

Double cannot represent 0.1 exactly, which makes it a poor tool for money. Foundation's Decimal stores decimal digits exactly, so 0.1 + 0.2 is exactly 0.3.

Swift Decimal for money

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Create decimals from strings (or integer literals). Writing Decimal(0.1) first creates a binary Double and inherits its imprecision. Decimal is slower and more verbose than Double; for money many teams simply store an integer number of cents (Int), which is exact, fast and trivial to compare.

Bit operations

For flags, masks and low-level code, integers support & (and), | (or), ^ (xor), ~ (not) and the shifts << and >>:

Swift Bits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

String(value, radix:) converts to text in any base from 2 to 36; Int(text, radix:) parses it back. Operators lists them all, and Working with Data and Bytes uses them in practice.

Formatting numbers

For display, use formatted() or String(format:):

Swift Formatting for display

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

formatted() is the modern API: type-safe, locale-aware (so digits and separators follow the user's region; our server uses a US-style locale) and chainable. String(format:) is the C-style printf family and needs Foundation; its format codes are %d for integers, %f for doubles and %x for hex. Do not pass Swift String values to %s; use interpolation for text. See String Interpolation and Formatting for a deeper treatment, and Foundation Number Types for NumberFormatter.

Currency, percent and grouping symbols depend on the machine's locale. A test that prints 1234.5.formatted(.currency(code: "USD")) may print $1,234.50 in one place and US$1,234.50 in another. For outputs that must be identical everywhere, pass an explicit locale or build the string yourself.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is -7 / 2 with Int values?

    Integer division truncates toward zero, so -7 / 2 is -3 (and -7 % 2 is -1).
  2. 2. What happens with var x: UInt8 = 255; x += 1?

    Ordinary arithmetic checks for overflow and stops the program. Use &+ if you want wrap-around.
  3. 3. Which expression wraps around on overflow instead of trapping?

    The ampersand operators &+, &- and &* are the explicit wrapping versions.
  4. 4. What does 2.5.rounded() return?

    The default rule rounds halves away from zero and the result stays a Double, so 3.0. Use .toNearestOrEven for banker's rounding.
  5. 5. Which is the best way to create the exact decimal 0.1 for money calculations?

    Decimal(0.1) starts from a binary Double and keeps its error. Parsing the string gives the exact decimal value.

Summary

  • Integer / truncates toward zero; % follows the sign of the left operand; use isMultiple(of:) for divisibility.
  • Overflow and integer division by zero trap; floating-point division follows IEEE 754 (inf, NaN).
  • Use &+, &-, &* and ...ReportingOverflow when wrapping is intended, and clamping: or truncatingIfNeeded: to convert between integer types.
  • rounded() accepts rules such as .up, .down, .towardZero and .toNearestOrEven.
  • pow, sqrt and trigonometry live in Foundation; Decimal (built from strings) and integer cents are for exact money.
  • Format numbers for display with formatted() or String(format:), and remember that output depends on locale.

Next: Strings