Lesson 30Collections
Collections Practice
Practice Projects
Let's put everything together with real-world mini-projects using all collection types!
Mini Projects
1. Student Gradebook
Dictionary of arrays to store and calculate grades
2. Shopping Cart
Array of dictionaries for cart items
3. Word Frequency
Dictionary to count word occurrences
4. Leaderboard
Set for unique scores, sorted display
Skills Used
ArraysSetsDictionariesmap/filter/reduceNested CollectionsSorting
Module Complete!
Congratulations! You've mastered Swift Collections. You can now store, access, and transform data like a pro!
Next up: Functions - learn to write reusable code!
main.swift
// PROJECT 1: Student Gradebook
var gradebook: [String: [Int]] = [
"Alice": [95, 88, 92, 90],
"Bob": [78, 85, 80, 88],
"Charlie": [92, 95, 98, 94]
]
// Calculate average for each student
for (name, grades) in gradebook {
let average = grades.reduce(0, +) / grades.count
print("\(name): \(average)")
}
// Find the top student
let topStudent = gradebook.max { a, b in
a.value.reduce(0, +) < b.value.reduce(0, +)
}
print("Top student: \(topStudent!.key)")
// PROJECT 2: Shopping Cart
var cart: [[String: Any]] = []
func addItem(name: String, price: Double, quantity: Int) {
cart.append([
"name": name,
"price": price,
"quantity": quantity
])
}
addItem(name: "Apple", price: 0.99, quantity: 5)
addItem(name: "Bread", price: 2.49, quantity: 2)
addItem(name: "Milk", price: 3.99, quantity: 1)
// Calculate total
var total = 0.0
for item in cart {
if let price = item["price"] as? Double,
let qty = item["quantity"] as? Int {
total += price * Double(qty)
}
}
print("Total: $\(String(format: "%.2f", total))")
// PROJECT 3: Word Frequency Counter
let text = "the quick brown fox jumps over the lazy dog"
let words = text.split(separator: " ")
var frequency: [String: Int] = [:]
for word in words {
let w = String(word)
frequency[w, default: 0] += 1
}
// Sort by frequency
let sorted = frequency.sorted { $0.value > $1.value }
for (word, count) in sorted {
print("\(word): \(count)")
}
// PROJECT 4: Leaderboard
var scores: Set<Int> = [100, 85, 92, 78, 95, 88]
// Add new scores
scores.insert(99)
scores.insert(85) // Already exists, ignored
// Get top 3
let top3 = Array(scores.sorted(by: >).prefix(3))
print("Top 3: \(top3)") // [100, 99, 95]Challenge!
Create your own project: a contact book that stores names, phone numbers, and email addresses. Include features to add, search, and list contacts!