Swift Numbers and Operators

Calculate with Swift's arithmetic, comparison and logical operators, avoid integer division surprises, and use rounding, random numbers and number formatting.

Lesson 3 of 43Beginner18 min read

Apps calculate constantly: a basket total, a tip, a countdown timer, the score in a game, a random tile in a puzzle. Swift uses the familiar symbols +, -, * and /, along with comparison operators like < and == and logical operators like &&.

Swift's arithmetic is strict and safe. You can't mix an Int and a Double without converting one of them. Dividing two Ints gives an Int, with the decimals dropped. And if a calculation goes beyond the largest number an Int can hold, Swift stops the program with an error rather than quietly producing a wrong answer, which is a deliberate safety feature.

In this lesson you'll use arithmetic and compound assignment, compare values and combine conditions, round results, find the larger or smaller of two values, generate random numbers and format decimals for display.

Arithmetic operators

OperatorMeaningInt exampleDouble example
+Add7 + 2 is 97.5 + 2 is 9.5
-Subtract7 - 2 is 57.5 - 2 is 5.5
*Multiply7 * 2 is 142.5 * 3 is 7.5
/Divide7 / 2 is 37.0 / 2 is 3.5
%Remainder7 % 2 is 1use truncatingRemainder

When both values are Int, / drops the decimals. Note that a literal like 2 adapts to whatever type it's used with, so 7.5 + 2 works, but a variable of type Int must be converted: Double(count) / 2. % only works with integers.

Compound assignment, and no ++

Update a variable based on its current value with:

ShortcutSame as
x += 5x = x + 5
x -= 5x = x - 5
x *= 2x = x * 2
x /= 2x = x / 2

Swift has no ++ or -- operators; they were removed because they made code harder to read. Write count += 1 instead. Operators follow the usual maths order: brackets, then *, / and %, then + and -.

Comparison and logical operators

Comparisons produce a Bool: ==, !=, <, >, <=, >=. They work on numbers and on strings, which compare alphabetically.

Combine conditions with && (and), || (or) and ! (not):

Swift
let age = 20
let hasTicket = true
print(age >= 18 && hasTicket)    // true
print(!hasTicket)                 // false

Swift stops evaluating early: in a && b, if a is false, b is never checked.

Rounding, min, max, random and formatting

  • (2.567).rounded() gives 3.0; for two decimals, round x * 100 and divide by 100.
  • .rounded(.down) and .rounded(.up) round down and up.
  • min(a, b), max(a, b) and abs(-7) work on any numbers.
  • Int.random(in: 1...6) gives a random whole number; Double.random(in: 0..<1) a random decimal; ["a", "b"].randomElement() picks an item.
  • To show a fixed number of decimals, use String(format: "%.2f", price) (it needs import Foundation) or, in modern Swift, price.formatted(.number.precision(.fractionLength(2))).

Integer sizes and their limits

Int is the right choice almost every time, but Swift also has sized integer types for special jobs:

TypeRange
Int8-128 to 127
UInt80 to 255 (one byte)
Int-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 on 64-bit devices
UInt0 upwards, unsigned

Every integer type has .min and .max, so print(Int.max) shows the largest Int. The U types can't hold negative numbers, and they're mainly for raw data such as bytes from a file. Stick with Int for counts and indexes, even ones that are never negative, because mixing types forces conversions everywhere.

Integer division always rounds towards zero, including for negative numbers: -7 / 2 is -3, and -7 % 2 is -1. The remainder takes the sign of the number on the left.

Why 0.1 + 0.2 is not exactly 0.3

Double stores numbers in binary, and many decimals, like 0.1, have no exact binary form. Tiny errors appear:

Swift
print(0.1 + 0.2)                        // 0.30000000000000004
print(0.1 + 0.2 == 0.3)                 // false
print(abs(0.1 + 0.2 - 0.3) < 1e-9)      // true

This isn't a Swift bug; every language that uses standard floating-point numbers behaves the same way. Never compare Doubles with == after a calculation. Check that the difference is very small instead, as in the last line. For money, keep amounts as whole pennies in an Int, or use Foundation's Decimal type, so totals always add up exactly.

Swift Operators Syntax

Operators

a + b   a - b   a * b   a / b   a % b
x += 1   x -= 1
a == b   a != b   a < b   a >= b
c1 && c2   c1 || c2   !c
(2.5).rounded()   min(a, b)   max(a, b)   abs(x)
Int.random(in: 1...6)
String(format: "%.2f", price)   // import Foundation

Swift Operators Summary

  • / between two Ints drops the decimals; convert with Double() to keep them.
  • % gives the remainder for integers; +=, -=, *= and /= update variables. There's no ++.
  • ==, !=, <, >, <= and >= compare; &&, || and ! combine Bools.
  • rounded(), min, max and abs handle common maths.
  • Int.random(in:) gives random numbers; String(format:) formats decimals.

Swift Operators Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Minutes, hours and even numbers

Swift
let minutes = 135
let hours = minutes / 60
let left = minutes % 60
print("\(minutes) minutes = \(hours) h \(left) min")

for n in 1...6 where n % 2 == 0 {
    print("\(n) is even")
}
Output
135 minutes = 2 h 15 min
2 is even
4 is even
6 is even
Line-by-line explanation
  1. Line 2Integer division gives the whole hours.
  2. Line 3The remainder is the minutes left over.
  3. Line 6where filters the loop: only numbers that divide by 2 with nothing over.
Example 2

Averages and rounding

Swift
let total = 17
let count = 4

print(total / count)
let average = Double(total) / Double(count)
print(average)
print((average * 10).rounded() / 10)
print(max(total, 20), min(3.5, 2.25), abs(-8))
Output
4
4.25
4.3
20 2.25 8
Line-by-line explanation
  1. Line 4Both are Ints, so the .25 is lost.
  2. Line 5Converting both to Double keeps the decimals.
  3. Line 7Multiply by 10, round, divide by 10: one decimal place. 42.5 rounds up to 43.
  4. Line 8max, min and abs work with any number type.
Example 3

Score updates and a dice roll

Swift
var score = 0
score += 50
score *= 2
score -= 15
score += 1
print("Score: \(score)")

let roll = Int.random(in: 1...6)
print("You rolled \(roll)")
print(roll >= 1 && roll <= 6)
Output
Score: 86
You rolled 4
true
Line-by-line explanation
  1. Lines 2 to 50, then 50, 100, 85 and finally 86. Swift has no ++, so += 1 adds one.
  2. Line 8random(in:) picks from a range that includes both ends; your number may differ.
  3. Line 10The roll is always within range, so this is always true.

Common Swift Operators Mistakes

Expecting / to keep decimals

Don't
let half = 1 / 2              // 0
Do
let half = 1.0 / 2            // 0.5

Using ++

Don't
var lives = 3
lives++                       // error: '++' is unavailable
Do
lives += 1

% with Doubles

Don't
let r = 7.5 % 2               // error: '%' is unavailable: use truncatingRemainder instead
Do
let r = 7.5.truncatingRemainder(dividingBy: 2)    // 1.5

Swift Operators in Real Projects

Numbers in apps

Shopping apps total baskets and apply discounts, fitness apps convert seconds into paces, and games roll dice and move characters every frame. For money, many apps use Foundation's Decimal type, which stores decimal values exactly, avoiding the tiny rounding errors of Double. Apple's formatted() APIs then display amounts in each user's currency and number style.

Swift Operators FAQ

How do I divide two integers and get a decimal in Swift?

Convert at least one of them to Double before dividing: Double(7) / Double(2) gives 3.5. Converting after the division is too late, because Double(7 / 2) is 3.0: the integer division has already dropped the decimals.

Why doesn't Swift have ++ and --?

They were removed in Swift 3 because they added little over += 1 and -= 1, and the difference between i++ and ++i caused confusing bugs in other languages. Write count += 1 instead.

What happens when an Int overflows in Swift?

The program stops with a runtime error rather than silently wrapping round to a wrong number. If you really want wrap-around, use the overflow operators &+, &- and &*, or methods such as addingReportingOverflow(_:) that tell you whether overflow happened.

How do I round a Double to 2 decimal places in Swift?

For calculations, use (value * 100).rounded() / 100. For display, format it instead of rounding the stored value: String(format: "%.2f", value) with Foundation imported, or value.formatted(.number.precision(.fractionLength(2))).

How do I get the remainder of a Double in Swift?

% only works with integers. For decimals, use truncatingRemainder(dividingBy:): 7.0.truncatingRemainder(dividingBy: 2) gives 1.0.

Swift Operators Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Complete the code so it shows the remainder of 17 divided by 5.

print(17  5)
Predict the outputeasy

What does print(9 / 2) show?

Predict the outputmedium

What does this print?

var x = 10
x -= 3
x *= 2
print(x)
Multiple choicemedium

How do you add one to a variable in Swift?

Multiple choicehard

What happens if an Int calculation goes past Int's maximum value?

Swift Operators Quiz

5 questions to check what you learned.

  1. What is 2 + 3 * 4 in Swift?

    • 14
    • 20
    • 24
    • 9
  2. What does Int.random(in: 1...6) return?

    • Always 1
    • A Double
    • An array of six numbers
    • A random whole number from 1 to 6, inclusive
  3. What does (3.6).rounded() return?

    • 3
    • 4.0
    • 3.0
    • 4
  4. What does !true evaluate to?

    • false
    • true
    • nil
    • An error
  5. Why does let x: Double = 7.5 + 2 compile when 7.5 + count (count an Int variable) doesn't?

    • It's a bug
    • Swift converts literals to strings
    • The literal 2 adapts to Double, but a variable already has a fixed type that must be converted
    • Variables can't be added