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
| Operator | Meaning | Int example | Double example |
|---|---|---|---|
+ | Add | 7 + 2 is 9 | 7.5 + 2 is 9.5 |
- | Subtract | 7 - 2 is 5 | 7.5 - 2 is 5.5 |
* | Multiply | 7 * 2 is 14 | 2.5 * 3 is 7.5 |
/ | Divide | 7 / 2 is 3 | 7.0 / 2 is 3.5 |
% | Remainder | 7 % 2 is 1 | use 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:
| Shortcut | Same as |
|---|---|
x += 5 | x = x + 5 |
x -= 5 | x = x - 5 |
x *= 2 | x = x * 2 |
x /= 2 | x = 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):
let age = 20
let hasTicket = true
print(age >= 18 && hasTicket) // true
print(!hasTicket) // falseSwift stops evaluating early: in a && b, if a is false, b is never checked.
Rounding, min, max, random and formatting
(2.567).rounded()gives3.0; for two decimals, roundx * 100and divide by 100..rounded(.down)and.rounded(.up)round down and up.min(a, b),max(a, b)andabs(-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 needsimport 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:
| Type | Range |
|---|---|
Int8 | -128 to 127 |
UInt8 | 0 to 255 (one byte) |
Int | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 on 64-bit devices |
UInt | 0 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:
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) // trueThis 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 FoundationSwift 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.
Minutes, hours and even numbers
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")
}135 minutes = 2 h 15 min
2 is even
4 is even
6 is evenLine-by-line explanation
- Line 2Integer division gives the whole hours.
- Line 3The remainder is the minutes left over.
- Line 6where filters the loop: only numbers that divide by 2 with nothing over.
Averages and rounding
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))4
4.25
4.3
20 2.25 8Line-by-line explanation
- Line 4Both are Ints, so the .25 is lost.
- Line 5Converting both to Double keeps the decimals.
- Line 7Multiply by 10, round, divide by 10: one decimal place. 42.5 rounds up to 43.
- Line 8max, min and abs work with any number type.
Score updates and a dice roll
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)Score: 86
You rolled 4
trueLine-by-line explanation
- Lines 2 to 50, then 50, 100, 85 and finally 86. Swift has no ++, so += 1 adds one.
- Line 8random(in:) picks from a range that includes both ends; your number may differ.
- Line 10The roll is always within range, so this is always true.
Common Swift Operators Mistakes
Expecting / to keep decimals
let half = 1 / 2 // 0let half = 1.0 / 2 // 0.5Using ++
var lives = 3
lives++ // error: '++' is unavailablelives += 1% with Doubles
let r = 7.5 % 2 // error: '%' is unavailable: use truncatingRemainder insteadlet r = 7.5.truncatingRemainder(dividingBy: 2) // 1.5Swift 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.
Complete the code so it shows the remainder of 17 divided by 5.
print(17 5)
What does print(9 / 2) show?
What does this print?
var x = 10
x -= 3
x *= 2
print(x)
How do you add one to a variable in Swift?
What happens if an Int calculation goes past Int's maximum value?
Swift Operators Quiz
5 questions to check what you learned.
What is
2 + 3 * 4in Swift?- 14
- 20
- 24
- 9
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
What does
(3.6).rounded()return?- 3
- 4.0
- 3.0
- 4
What does
!trueevaluate to?- false
- true
- nil
- An error
Why does
let x: Double = 7.5 + 2compile when7.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