Lesson 29Collections
Nested Collections
Collections Inside Collections
You can put collections inside other collections to create complex data structures like grids, tables, and hierarchies!
Types of Nested Collections
[[Int]]Array of arrays (2D grid)
[[String: Any]]Array of dictionaries
[String: [String]]Dictionary of arrays
[String: [String: Int]]Dictionary of dictionaries
Accessing Nested Data
Use multiple subscripts to dig deeper:
grid[0][1]- Row 0, Column 1students[0]["name"]- First student's nameschedule["Monday"]![0]- First class Monday
Common Use Cases
- Game boards - 2D arrays for tic-tac-toe, chess
- Student records - Array of dictionaries
- Weekly schedules - Dictionary of arrays
- Organizational data - Nested dictionaries
main.swift
// NESTED ARRAYS (2D Arrays)
// Like a grid or table!
var grid: [[Int]] = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
// Accessing elements
print(grid[0]) // [1, 2, 3] - first row
print(grid[0][1]) // 2 - first row, second column
print(grid[2][2]) // 9 - third row, third column
// Modifying nested arrays
grid[1][1] = 50
print(grid[1]) // [4, 50, 6]
// Iterating nested arrays
for row in grid {
for number in row {
print(number, terminator: " ")
}
print() // New line after each row
}
// ARRAY OF DICTIONARIES
let students: [[String: Any]] = [
["name": "Alice", "age": 12, "grade": "A"],
["name": "Bob", "age": 13, "grade": "B"],
["name": "Charlie", "age": 12, "grade": "A"]
]
// Access nested dictionary
print(students[0]["name"]!) // Alice
for student in students {
if let name = student["name"] as? String {
print("Student: \(name)")
}
}
// DICTIONARY OF ARRAYS
let schedule: [String: [String]] = [
"Monday": ["Math", "English", "Science"],
"Tuesday": ["Art", "Music", "PE"],
"Wednesday": ["History", "Geography"]
]
// Access nested array
print(schedule["Monday"]!) // ["Math", "English", "Science"]
print(schedule["Monday"]![0]) // Math
// DICTIONARY OF DICTIONARIES
let school: [String: [String: Int]] = [
"ClassA": ["Alice": 95, "Bob": 87],
"ClassB": ["Charlie": 92, "David": 88]
]
// Access nested value
print(school["ClassA"]!["Alice"]!) // 95
// Flatten nested arrays
let nestedNumbers = [[1, 2], [3, 4], [5, 6]]
let flat = nestedNumbers.flatMap { $0 }
print(flat) // [1, 2, 3, 4, 5, 6]Try It Yourself!
Create a 3x3 tic-tac-toe board using a 2D array. Initialize it with empty strings, then place some X's and O's!