Chapter 64: Overview
Overview
1. The Big Picture: Why Swift gives you three main collections
Swift gives you three primary collection types because almost every real program needs to solve one (or more) of these three problems:
- I have an ordered list of things — and order matters, duplicates are okay → Array[Element]
- I have a group of unique things — order doesn’t matter, I just want fast “does it contain X?” → Set<Element>
- I have items that I want to find quickly by a label/key — like a phone book or settings dictionary → Dictionary[Key: Value]
| You want… | Almost always use | Ordered? | Duplicates allowed? | Fast “contains X”? | Fast “get value for key X”? | Typical real-life examples |
|---|---|---|---|---|---|---|
| Ordered list, duplicates ok | Array | Yes | Yes | Slow (linear search) | No | shopping cart, messages, tasks, search results, history |
| Unique items, fast “is X in the group?” | Set | No | No | Very fast (hash) | No | tags, permissions, unique IDs, friends (no duplicates) |
| Key → value lookup | Dictionary | No | Yes (different keys) | No | Very fast (hash) | user profile, settings, JSON data, lookup tables |
Golden rule you should memorize forever:
- Need order or duplicates → almost always Array
- Need uniqueness + fast “contains?” → Set
- Need fast lookup by key → Dictionary
2. Arrays – the workhorse (you will use this 70–80% of the time)
Creating arrays
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
// Most common ways let days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] var cart: [String] = [] // empty mutable array var scores = [Int]() // another empty style let repeated = Array(repeating: 0, count: 6) // [0, 0, 0, 0, 0, 0] |
Basic real operations
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
var playlist = ["Shape of You", "Blinding Lights"] playlist.append("Levitating") // add at end playlist.append(contentsOf: ["Bad Habits", "As It Was"]) playlist.insert("Flowers", at: 1) // insert at position playlist[0] = "Stay" // replace let removed = playlist.remove(at: 3) // remove & get value let lastSong = playlist.removeLast() print(playlist.count) // current size print(playlist.isEmpty) // false print(playlist.contains("Levitating")) // true |
Real-life example: Shopping cart summary
|
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 29 |
struct CartItem { let name: String let price: Double let quantity: Int } var cart: [CartItem] = [] cart.append(CartItem(name: "Wireless Earbuds", price: 3499, quantity: 1)) cart.append(CartItem(name: "Phone Case", price: 799, quantity: 2)) cart.append(CartItem(name: "Screen Protector", price: 499, quantity: 1)) var total: Double = 0 print("Your Cart (\(cart.count) items)") for (index, item) in cart.enumerated() { let lineTotal = item.price * Double(item.quantity) total += lineTotal print("\(index + 1). \(item.name) × \(item.quantity) = ₹\(String(format: "%.2f", lineTotal))") } print("──────────────────────────────") print("Total: ₹\(String(format: "%.2f", total))") |
3. Sets – when uniqueness matters
Creating & basic 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 |
var activeFeatures = Set<String>() activeFeatures.insert("darkMode") activeFeatures.insert("notifications") activeFeatures.insert("darkMode") // ignored – already present print(activeFeatures) // Set(["darkMode", "notifications"]) activeFeatures.insert("offlineMode") print(activeFeatures.contains("offlineMode")) // true print(activeFeatures.contains("analytics")) // false // Remove activeFeatures.remove("notifications") // Combine sets let adminFeatures = Set(["editUsers", "viewAnalytics"]) let allFeatures = activeFeatures.union(adminFeatures) |
Real-life example: User permissions / roles
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
var currentUserPermissions = Set<String>() currentUserPermissions.insert("read") currentUserPermissions.insert("write") currentUserPermissions.insert("moderate") if currentUserPermissions.contains("moderate") { print("You can moderate content") } if currentUserPermissions.isSuperset(of: ["read", "write"]) { print("You have read & write access") } // Remove permission currentUserPermissions.remove("moderate") |
4. Dictionaries – key → value lookup
Creating & basic 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 26 27 28 29 30 31 |
var userInfo: [String: Any] = [ "name": "Rahul Verma", "age": 27, "city": "Bengaluru", "isPremium": true, "points": 14520 ] // Read if let name = userInfo["name"] as? String { print("Name: \(name)") } // Update userInfo["points"] = 15000 // Add userInfo["favoriteColor"] = "Blue" // Remove userInfo["age"] = nil // Loop for (key, value) in userInfo { print("\(key): \(value)") } |
Better style (strongly typed keys)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
enum UserKey: String { case name case age case city case isPremium } var typedUser: [UserKey: Any] = [ .name: "Sneha Reddy", .age: 24, .isPremium: true ] |
Real-life example: Settings / config
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
var appSettings: [String: Any] = [ "theme": "dark", "fontSize": 16, "notificationsEnabled": true, "language": "en-IN", "locationSharing": false ] // Apply settings if let theme = appSettings["theme"] as? String { applyTheme(theme) } if let fontSize = appSettings["fontSize"] as? CGFloat { setFontSize(fontSize) } |
5. Quick Comparison Table (keep this in your mind)
| You want to… | Choose this | Ordered? | Duplicates? | Fast “contains X”? | Fast “get value for key X”? | Typical real-life examples |
|---|---|---|---|---|---|---|
| Keep order, allow duplicates | Array | Yes | Yes | Slow | No | cart, messages, tasks, history, search results |
| Ensure uniqueness, fast “is X here?” | Set | No | No | Very fast | No | tags, permissions, unique IDs, friends (no dupes) |
| Fast lookup by key | Dictionary | No | Yes (keys unique) | No | Very fast | user profile, settings, JSON, config, lookup tables |
6. Small Practice – Try these right now
- Array Create array of 6 favorite songs → Print them numbered → Add one more at the beginning → Remove the last one
- Set Create set of 7 tags (some duplicates) → Add 2 more → Check if “Swift” is present → Print all unique tags
- Dictionary Create dictionary for a user profile → “name”, “age”, “city”, “isPremium” → Print all key-value pairs → Change age and add “favoriteColor”
Paste your code here if you want feedback or want to see more polished versions!
What would you like to explore next?
- Array slicing & memory behavior with ArraySlice
- Sorting arrays (simple & custom comparators)
- Filtering, mapping, reducing in depth
- Dictionaries with typed keys & default values
- Sets operations (union, intersection, symmetric difference)
- Collections in SwiftUI (List, ForEach, @State)
Just tell me — we’ll continue in the same clear, patient, detailed style 😊
