Chapter 36: Arrays
1. What is an Array in Swift? (the big picture)
An array is an ordered collection of values of the same type.
Think of it as:
- a numbered list
- a shopping list written in order
- seats in a movie theater row (each seat has a number 0, 1, 2, …)
Important facts about Swift arrays:
- Ordered — items keep the order you put them in
- Indexed — first item is at index 0, second at 1, etc.
- Type-safe — all elements must be the same type
- Dynamic — can grow or shrink at any time (when using var)
- Value type — when you assign or pass an array, a copy is made
- Immutable when let — you can read items, but cannot add/remove/change them
- Mutable when var — you can add, remove, change items
|
0 1 2 3 4 5 6 7 |
let fixedNumbers = [1, 2, 3, 4] // cannot add or remove items var changeableNames = ["Aarav", "Priya"] // can add more later |
2. Creating Arrays — all the common ways
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// 1. Most common — array literal let fruits = ["Mango", "Banana", "Apple", "Orange", "Guava"] // 2. Empty array — two very common styles var empty1: [String] = [] // explicit type + empty literal var empty2 = [Int]() // inferred type + empty initializer // 3. Array with repeated values (very useful) let fiveZeros = Array(repeating: 0, count: 5) // [0, 0, 0, 0, 0] let tenStars = Array(repeating: "⭐", count: 10) // 4. From other collections / sequences let numbers = Array(1...10) // [1, 2, 3, ..., 10] let doubled = numbers.map { $0 * 2 } // [2, 4, 6, ..., 20] |
3. Reading from Arrays — the most frequent operations
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] // Count print(days.count) // 5 // Is empty? print(days.isEmpty) // false // Access by index (0-based!) print(days[0]) // Monday print(days[4]) // Friday print(days[days.count - 1]) // Friday (last item) // Safer access — first & last are optional print(days.first ?? "No first") // Monday print(days.last ?? "No last") // Friday // Check if contains print(days.contains("Sunday")) // false print(days.contains("Tuesday")) // true |
Important safety note: Accessing invalid index crashes at runtime:
|
0 1 2 3 4 5 6 |
print(days[10]) // Fatal error: Index out of range |
→ Always check bounds before using index:
|
0 1 2 3 4 5 6 7 8 |
if days.indices.contains(3) { print(days[3]) } |
4. Modifying Arrays — when using var
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
var shoppingList = ["Milk", "Bread", "Eggs"] // Add at the end (most common) shoppingList.append("Butter") // Add multiple items shoppingList.append(contentsOf: ["Cheese", "Tomatoes"]) // Insert at specific position shoppingList.insert("Honey", at: 1) // now: ["Milk", "Honey", "Bread", …] // Replace item at index shoppingList[0] = "Almond Milk" // Remove let removed = shoppingList.remove(at: 2) // removes "Bread", returns it let last = shoppingList.removeLast() // removes last item // Remove all items that match a condition shoppingList.removeAll { $0.contains("Milk") } // Clear entire array shoppingList.removeAll() |
5. Looping over Arrays — the three most common styles
Style 1 — simplest (most used)
|
0 1 2 3 4 5 6 7 8 9 10 |
let fruits = ["Mango", "Banana", "Apple", "Orange"] for fruit in fruits { print("I like \(fruit)") } |
Style 2 — with index (very frequent)
|
0 1 2 3 4 5 6 7 8 |
for (index, fruit) in fruits.enumerated() { print("\(index + 1). \(fruit)") } |
Style 3 — when you only need the index
|
0 1 2 3 4 5 6 7 8 |
for index in fruits.indices { print("Position \(index): \(fruits[index])") } |
6. Very Common Real-Life Examples
Example 1 – Shopping cart / order list
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
var cart: [String] = [] cart.append("iPhone 16") cart.append("AirPods Pro 2") cart.append("MagSafe Charger") // Insert at beginning (newest first) cart.insert("Screen Protector", at: 0) print("Items in cart (\(cart.count)):") for (i, item) in cart.enumerated() { print(" \(i + 1). \(item)") } |
Example 2 – To-do list with completion status
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
struct Task { let title: String var isDone: Bool } var tasks = [ Task(title: "Finish Swift lesson", isDone: false), Task(title: "Buy groceries", isDone: true), Task(title: "Call mom", isDone: false) ] // Mark one as done if let index = tasks.firstIndex(where: { $0.title == "Call mom" }) { tasks[index].isDone = true } // Show only pending tasks let pending = tasks.filter { !$0.isDone } print("Pending tasks: \(pending.count)") |
Example 3 – Scoreboard / leaderboard
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
let names = ["Rahul", "Priya", "Aarav", "Sneha"] let scores = [920, 980, 850, 950] // Combine and sort descending let leaderboard = zip(names, scores) .sorted { $0.1 > $1.1 } // sort by score descending for (position, (name, score)) in leaderboard.enumerated() { print("\(position + 1). \(name) - \(score) points") } |
7. Very Common Beginner Mistakes & Correct Habits
| Mistake | Wrong / Dangerous code | Correct / Safe habit | Why? |
|---|---|---|---|
| Force-unwrapping first/last | fruits.first! | fruits.first ?? “None” or if let | Array can be empty → crash |
| Modifying let array | let arr = [1]; arr.append(2) | Use var if you need to change | let arrays are immutable |
| Accessing index without bounds check | arr[10] | if arr.indices.contains(10) { … } | Out-of-bounds → fatal crash |
| Mutating array while iterating | for item in arr { arr.append(item) } | Build new array or use indices | Runtime error: collection mutated |
| Forgetting arrays are value types | var a = b; a.append(1) → b changes | Normal — copy is made | Safety feature |
8. Quick Reference – Most Used Array Operations
| Goal | Best modern code | Returns / modifies original? |
|---|---|---|
| Add one item | arr.append(item) | modifies original |
| Add multiple | arr.append(contentsOf: […]) | modifies original |
| Insert at position | arr.insert(item, at: index) | modifies original |
| Remove at index | arr.remove(at: index) | returns removed item |
| Remove last | arr.removeLast() | returns removed item |
| Clear all | arr.removeAll() | modifies original |
| Check contains | arr.contains(value) | Bool |
| First / last (safe) | arr.first / arr.last | Optional |
| Loop with index | for (i, item) in arr.enumerated() { … } | — |
| Filter | arr.filter { $0 > 10 } | new array |
| Transform | arr.map { $0 * 2 } | new array |
| Join to string | arr.joined(separator: “, “) | new string |
9. Small Practice – Try these now
- Create an array of 5 favorite movies → print them numbered → add one more at the beginning → remove the last one → check if “Inception” is in the list
- Create array of numbers 1…10 → filter only even numbers → multiply each by 3 → join them with ” → ” separator
Paste your code here if you want feedback or corrections!
What would you like to explore next about arrays?
- Array slicing (subarrays, prefix, dropFirst…)
- Sorting arrays & custom sorting
- Dictionaries (key-value collections)
- Sets (unique values, no duplicates)
- Advanced operations (reduce, compactMap, flatMap…)
- Arrays in SwiftUI (List, ForEach, @State)
Just tell me — we’ll continue in the same clear, patient, detailed style 😊
