Chapter 24: Swift Arithmetic Operators
1. What are Arithmetic Operators?
Arithmetic operators are the mathematical symbols you use to perform calculations:
- + addition
- – subtraction
- * multiplication
- / division
- % remainder (modulo)
These operators work with numeric types:
- Int (whole numbers)
- Double (decimals – most common for real-world math)
- Float (less common)
- Decimal (exact decimals – used for money)
2. Basic Arithmetic Operators – with examples
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
let a = 20 let b = 7 print(a + b) // 27 print(a - b) // 13 print(a * b) // 140 print(a / b) // 2 ← integer division → drops the decimal part print(a % b) // 6 ← remainder after division |
Important difference when using floating-point numbers:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
let x = 20.0 let y = 7.0 print(x + y) // 27.0 print(x - y) // 13.0 print(x * y) // 140.0 print(x / y) // 2.857142857142857 ← keeps decimals print(x.truncatingRemainder(dividingBy: y)) // 6.0 |
Realistic example – price calculation
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
let basePrice: Double = 1499.99 let quantity = 3 let taxRate: Double = 0.18 let subtotal = basePrice * Double(quantity) // 4499.97 let taxAmount = subtotal * taxRate // 809.9946 let finalAmount = subtotal + taxAmount // 5309.9646 print("Final price: ₹\(finalAmount)") // Final price: ₹5309.9646 |
3. Compound Assignment Operators – very common shorthand
These combine an operation with assignment.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
var score = 150 score += 100 // score = score + 100 → 250 score -= 50 // → 200 score *= 2 // → 400 score /= 4 // → 100 score %= 7 // → 2 (remainder after 100 ÷ 7) print(score) // 2 |
Real-life pattern – accumulating totals
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
var cartTotal: Decimal = 0 cartTotal += 1499.99 // phone cartTotal += 899.00 // case cartTotal += 299.50 // screen protector cartTotal += cartTotal * 0.18 // add 18% GST print("Cart total with tax: ₹\(cartTotal)") |
4. Unary Minus Operator – changing sign
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
let positive = 42 let negative = -positive // -42 var temperature = 36.6 temperature = -temperature // -36.6 let debt = -5000.75 print(debt) // -5000.75 |
Very common use case – reversing direction
|
0 1 2 3 4 5 6 7 |
var velocity = 50.0 // moving right velocity = -velocity // now moving left |
5. Increment / Decrement Operators – ++ and —
These exist in Swift, but they are very rarely used in modern code.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
var count = 0 count += 1 // preferred style count += 1 // Old style (still works, but most developers avoid it now) count++ // postfix – returns old value, then increments ++count // prefix – increments first, then returns new value |
Modern & clearer way (what you’ll see in real code 2024–2026):
|
0 1 2 3 4 5 6 7 8 9 10 11 |
var index = 0 for _ in 1...5 { index += 1 print("Item \(index)") } |
Why ++ and — are avoided in modern Swift:
- They can make code harder to read
- They behave differently depending on prefix/postfix
- += 1 is clearer and safer
6. Arithmetic with Decimal – very important for money
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import Foundation let coffeePrice: Decimal = 149.50 let quantity = 4 let discountPercent: Decimal = 10 var total = coffeePrice * Decimal(quantity) // 598.00 let discountAmount = total * (discountPercent / 100) // 59.80 total -= discountAmount // 538.20 let gst = total * 0.18 // 96.876 total += gst // 635.076 print("Final bill: ₹\(total)") // Final bill: ₹635.076 |
Important note:
- Never do money math with Double → floating-point errors
- Always use Decimal for currency
7. Very Common Beginner Mistakes & Correct Habits
| Mistake | Wrong / Dangerous code | Correct / Better habit | Why? |
|---|---|---|---|
| Doing money math with Double | total += 0.1 many times | Use Decimal for prices | Avoids 0.30000000000000004 bugs |
| Using / with Int and expecting decimals | 10 / 3 → 3 | 10.0 / 3.0 or Double(10) / 3 | Integer division truncates |
| Writing x++ in complex expressions | array[x++] | array[x]; x += 1 | Much clearer, avoids bugs |
| Forgetting to convert types | price * quantity where quantity is Int | price * Decimal(quantity) | Prevents type mismatch |
| Using % with negative numbers carelessly | -10 % 3 | Be aware: Swift gives positive remainder | -10 % 3 == 2 in Swift |
8. Quick Reference – Arithmetic Operators Cheat Sheet
| Operator | Meaning | Example | Result | Most common real use |
|---|---|---|---|---|
| + | Addition | a + b | sum | Totals, concatenating strings |
| – | Subtraction | a – b | difference | Discounts, differences |
| * | Multiplication | price * quantity | product | Subtotal, scaling |
| / | Division | total / count | quotient | Average, splitting amounts |
| % | Remainder (modulo) | value % 2 | remainder | Checking even/odd, cycling values |
| += -= *= /= %= | Compound assignment | score += 100 | update | Accumulating scores, totals, counters |
| – (unary) | Negation | -value | negative | Reverse direction, debt |
9. Small Practice – Try these now
- Calculate final price: base price = 2499.99 quantity = 2 discount = 20% GST = 18% → what is the final amount?
- Check if a number is divisible by 5 let number = 125 → use % and print “Divisible” or “Not divisible”
- Update a counter every time an item is added to cart var itemCount = 0 → add 3 items, then add 2 more
Paste your attempts if you want feedback!
What would you like to explore next?
- Arithmetic with Decimal in more detail (money examples)
- How to avoid floating-point surprises
- Rounding numbers (round, ceil, floor)
- Random numbers (Int.random(in:), Double.random(in:))
- Or move to another group of operators (comparison, logical, range…)
Just tell me — we’ll continue in the same detailed, patient, teacher-like style 😊
