Swift Arrays
An array stores multiple values of the same type in an ordered list. Each value sits at a numbered position called an index. Arrays are one of the most used data structures in Swift programming.
The Train Compartment Analogy
┌─────────────────────────────────────────────────┐
│ Array = A train with numbered compartments │
│ │
│ Index: [0] [1] [2] [3] │
│ Value: "Apple" "Mango" "Banana" "Grapes" │
│ │
│ Each compartment holds one item. │
│ The first compartment is always index 0. │
└─────────────────────────────────────────────────┘
Creating an Array
// With values
let fruits = ["Apple", "Mango", "Banana"]
// Empty array with type annotation
var scores: [Int] = []
// Another empty array syntax
var names = [String]()
Accessing Elements
let cities = ["Delhi", "Mumbai", "Chennai", "Kolkata"]
print(cities[0]) // Delhi
print(cities[2]) // Chennai
print(cities.first ?? "None") // Delhi
print(cities.last ?? "None") // Kolkata
Array indexes start at 0. Accessing an index that does not exist crashes your app, so always verify the index or use safe access like first and last.
Array Properties
let numbers = [10, 20, 30, 40, 50]
print(numbers.count) // 5
print(numbers.isEmpty) // false
print(numbers.contains(30)) // true
Adding Elements
var colors = ["Red", "Green"]
colors.append("Blue") // adds at end
colors.insert("Yellow", at: 1) // adds at index 1
print(colors) // ["Red", "Yellow", "Green", "Blue"]
Removing Elements
var animals = ["Cat", "Dog", "Fish", "Bird"]
animals.remove(at: 1) // removes "Dog"
animals.removeLast() // removes "Bird"
animals.removeFirst() // removes "Cat"
print(animals) // ["Fish"]
Updating Elements
var temps = [30, 32, 28, 35]
temps[2] = 31
print(temps) // [30, 32, 31, 35]
Iterating Over an Array
let languages = ["Swift", "Python", "Java"]
// With value only
for lang in languages {
print(lang)
}
// With index and value
for (index, lang) in languages.enumerated() {
print("\(index): \(lang)")
}
// 0: Swift
// 1: Python
// 2: Java
Array Operations
let a = [1, 2, 3]
let b = [4, 5, 6]
let combined = a + b
print(combined) // [1, 2, 3, 4, 5, 6]
Useful Array Methods
var nums = [5, 2, 8, 1, 9, 3]
print(nums.sorted()) // [1, 2, 3, 5, 8, 9]
print(nums.reversed()) // [3, 9, 1, 8, 2, 5]
print(nums.min()!) // 1
print(nums.max()!) // 9
let doubled = nums.map { $0 * 2 }
print(doubled) // [10, 4, 16, 2, 18, 6]
let evens = nums.filter { $0 % 2 == 0 }
print(evens) // [2, 8]
2D Arrays – Array of Arrays
let grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(grid[1][2]) // 6 (row 1, column 2)
┌─────────────────────────────────┐
│ grid visualised as a matrix │
│ │
│ [0] → 1 2 3 │
│ [1] → 4 5 6 │
│ [2] → 7 8 9 │
│ │
│ grid[1][2] = row 1, col 2 = 6 │
└─────────────────────────────────┘
