Chapter 63: Swift Collections
The Big Picture: What are Collections and Why Three Main Types?
A collection in Swift is any type that holds zero or more values.
Swift gives you three main choices for everyday work — each solves a different problem:
| Collection Type | Ordered? | Allows duplicates? | Fast lookup by value? | Fast lookup by key? | Most common real-life feeling | Typical use case examples |
|---|---|---|---|---|---|---|
| Array | Yes | Yes | No (slow) | No | “I have a list of things in a specific order” | shopping cart, to-do list, recent searches, messages |
| Set | No | No | Yes (very fast) | No | “I have a group of unique items — order doesn’t matter” | tags, permissions, unique IDs, friends list (no duplicates) |
| Dictionary | No (insertion order since Swift 4.2) | Yes (different keys) | No | Yes (very fast) | “I have items and I want to find them by a key/label” | user profile, JSON data, settings, lookup tables |
Golden rule you should burn into your mind:
- Need order or duplicates → almost always Array
- Need uniqueness and fast “does it contain X?” → Set
- Need fast lookup by key (“give me value for this name/ID”) → Dictionary
Chapter 2 – Arrays (the most common collection – you will use this 70–80% of the time)
2.1 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 |
// Most common ways let colors: [String] = ["Red", "Green", "Blue"] // type annotation optional var shoppingCart = [String]() // empty mutable array // Add items shoppingCart.append("Milk") shoppingCart.append(contentsOf: ["Bread", "Eggs"]) // Insert at specific position shoppingCart.insert("Butter", at: 1) // Replace shoppingCart[0] = "Almond Milk" // Remove shoppingCart.remove(at: 2) // removes "Eggs" let lastItem = shoppingCart.removeLast() // Count & empty check print(shoppingCart.count) // 2 print(shoppingCart.isEmpty) // false // Safe first/last let first = shoppingCart.first ?? "No items" |
2.2 Real-life example – shopping cart / order 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 30 31 32 |
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)) print("Your Cart (\(cart.count) items)") print("──────────────────────────────") var total: Double = 0 for (index, item) in cart.enumerated() { let lineTotal = item.price * Double(item.quantity) total += lineTotal print("\(index + 1). \(item.name) × \(item.quantity)") print(" ₹\(String(format: "%.2f", item.price)) each → ₹\(String(format: "%.2f", lineTotal))") print("──") } print("Grand Total: ₹\(String(format: "%.2f", total))") |
Chapter 3 – Sets (when uniqueness matters)
3.1 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 |
var tags = Set<String>() tags.insert("Swift") tags.insert("iOS") tags.insert("Beginner") tags.insert("Swift") // duplicate – ignored print(tags) // Set(["Swift", "iOS", "Beginner"]) print(tags.contains("Swift")) // true print(tags.contains("Python")) // false // Add multiple tags.formUnion(["Apple", "Xcode"]) // Remove tags.remove("Beginner") // Count print(tags.count) // 5 |
Real-life example – unique permissions / roles
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
var userPermissions = Set<String>() userPermissions.insert("read") userPermissions.insert("write") userPermissions.insert("delete") userPermissions.insert("read") // ignored if userPermissions.contains("delete") { print("User can delete content") } if userPermissions.isSuperset(of: ["read", "write"]) { print("User has read & write access") } |
Chapter 4 – Dictionaries (lookup by key)
4.1 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 profile: [String: Any] = [ "name": "Rahul Verma", "age": 27, "city": "Bengaluru", "isPremium": true, "points": 14520 ] // Access if let name = profile["name"] as? String { print("Name: \(name)") } // Update profile["points"] = 15000 // Add new profile["favoriteColor"] = "Blue" // Remove profile["age"] = nil // Loop for (key, value) in profile { print("\(key): \(value)") } |
Real-life example – user profile / settings
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
var userSettings: [String: Any] = [ "darkMode": true, "notificationsEnabled": true, "fontSize": 16, "language": "en", "locationSharing": false ] // Apply settings if let darkMode = userSettings["darkMode"] as? Bool, darkMode { applyDarkTheme() } if let fontSize = userSettings["fontSize"] as? CGFloat { setFontSize(fontSize) } |
Modern style (strongly typed dictionary)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
enum SettingKey: String { case darkMode case notificationsEnabled case fontSize case language } var typedSettings: [SettingKey: Any] = [ .darkMode: true, .fontSize: 16 ] |
Chapter 5 – Quick Comparison Table (keep this in mind)
| You want to… | Use this collection | Typical operations | Example real-life case |
|---|---|---|---|
| Keep order, allow duplicates | Array | append, insert(at:), remove(at:), enumerated() | shopping cart, task list, chat messages |
| Ensure uniqueness, fast “contains?” | Set | insert, contains, remove, union/intersection | tags, permissions, unique IDs, friends (no dupes) |
| Fast lookup by key | Dictionary | [key] = value, updateValue(forKey:), removeValue | user profile, settings, JSON data, lookup tables |
Chapter 6 – Small Practice – Try these
- Create an array of 5 favorite foods → Print them numbered → Add one more at the beginning → Remove the last one
- Create a set of 6 tags (some duplicates) → Add 2 more → Check if “Swift” is present → Print all unique tags
- Create a 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 slices
- Sorting arrays (simple & custom comparators)
- Filtering, mapping, reducing in depth
- Dictionaries in more depth (typed keys, default values)
- Sets operations (union, intersection, difference)
- Or move to another topic (optionals, switch, functions…)
Just tell me — we’ll continue in the same clear, patient, detailed style 😊
