Chapter 25: Swift Assignment Operators
1. What are Assignment Operators?
An assignment operator is used to assign a value to a variable or constant (or more generally: to a place in memory).
The most basic one is the single = sign:
|
0 1 2 3 4 5 6 7 |
let name = "Priya" // assign string "Priya" to constant name var score = 0 // assign 0 to variable score |
But Swift has a whole family of assignment operators — the most important ones are the compound assignment operators.
2. The Basic Assignment Operator: =
|
0 1 2 3 4 5 6 7 8 9 10 |
var temperature = 28.5 // initial value temperature = 29.2 // change value later let maxUsers = 1000 // can only be assigned once // maxUsers = 1500 // ❌ compile error – cannot re-assign let |
Important rule (very important mindset):
- Use let when the value will never change after the first assignment
- Use var when the value will be replaced with a new value later
This is not just style — it’s one of the strongest safety features of Swift.
3. Compound Assignment Operators — the ones you use every day
These combine an arithmetic operation with assignment in one step.
| Operator | Meaning | Equivalent to | Most common real use case |
|---|---|---|---|
| += | Add and assign | x = x + y | Accumulating scores, totals, counters |
| -= | Subtract and assign | x = x – y | Reducing lives, applying discounts |
| *= | Multiply and assign | x = x * y | Scaling values, doubling, taxes |
| /= | Divide and assign | x = x / y | Averaging, shrinking values |
| %= | Remainder and assign | x = x % y | Cycling values, checking patterns |
Live examples – try these right now
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
var points = 150 points += 100 // 250 points -= 30 // 220 points *= 2 // 440 points /= 4 // 110 points %= 7 // 5 (110 % 7 = 5) print(points) // 5 |
4. Real-life examples – how compound assignment is actually used
Example 1 – Shopping cart total
|
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 // charger cartTotal += cartTotal * 0.18 // add 18% GST print("Final cart: ₹\(cartTotal)") |
Example 2 – Game score & lives
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
var score = 0 var lives = 3 // player collects coin score += 100 lives -= 1 // hit obstacle // bonus round score *= 2 print("Score: \(score), Lives: \(lives)") |
Example 3 – Progress bar / percentage
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
var completedTasks = 0 let totalTasks = 12 completedTasks += 1 // finish one task completedTasks += 3 // finish three more let progress = Double(completedTasks) / Double(totalTasks) * 100 print("Progress: \(progress)%") // e.g. 33.333... |
Example 4 – Cycling / wrapping values (using %=)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
var currentPage = 0 let totalPages = 5 // user clicks "next" currentPage += 1 currentPage %= totalPages // wraps around: 0,1,2,3,4,0,1,... print("Showing page \(currentPage + 1)") |
5. Very Common Beginner Mistakes & Correct Habits
| Mistake | Wrong / Risky code | Correct / Better habit | Why? |
|---|---|---|---|
| Using = instead of += in loops | total = total + price every time | total += price | Shorter, clearer, less typing mistakes |
| Trying to use += on let | let count = 0; count += 1 | Use var if value must change | let cannot be reassigned |
| Doing money math with += on Double | total += 0.1 many times | Use Decimal for money | Avoids floating-point rounding errors |
| Writing x =+ 5 (wrong order) | score =+ 100 | score += 100 | =+ is not valid syntax |
| Forgetting to declare variable first | count += 1 without previous declaration | var count = 0; count += 1 | Must exist before modifying |
6. Quick Reference – Assignment Operators Cheat Sheet
| Operator | Meaning | Equivalent longer form | Most common real-world use case |
|---|---|---|---|
| = | Simple assignment | — | Initial value, one-time setting |
| += | Add and assign | x = x + y | Accumulating totals, scores, counters |
| -= | Subtract and assign | x = x – y | Decreasing lives, applying discounts |
| *= | Multiply and assign | x = x * y | Doubling values, calculating tax/growth |
| /= | Divide and assign | x = x / y | Averaging, shrinking progress bars |
| %= | Remainder and assign | x = x % y | Cycling pages, checking even/odd, wrapping |
7. Small Practice – Try these right now
Copy and complete these:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// 1. Shopping cart with discount & tax var total: Decimal = 0 total += 2499.99 // laptop total += 799.00 // mouse // apply 15% discount // add 18% GST // print final amount // 2. Progress counter var completed = 0 let totalSteps = 10 completed += 4 completed += 3 // use /= to calculate fraction completed // print percentage (multiply by 100) |
Would you like to go deeper into any part?
- More real examples with Decimal (money, invoices, discounts)
- How to combine arithmetic + comparison + assignment
- Using arithmetic operators in loops and animations
- Common patterns in games, forms, shopping apps
- Or move to another group of operators (comparison, logical, range…)
Just tell me — we’ll keep going in the same clear, patient, teacher-like style 😊
