Swift Collections

📦 Swift Collections – Complete Beginner to Interview Guide
In Swift, collections are used to store multiple values in a single variable.
Swift provides three main collection types:
1️⃣ Array
2️⃣ Dictionary
3️⃣ Set
These are core concepts for Swift programming, exams, and interviews.
1️⃣ Array in Swift ⭐
An Array stores an ordered list of values of the same type.
Declaration
Access Elements
Output
Add Elements
Output
Loop Through Array
2️⃣ Dictionary in Swift ⭐⭐
A Dictionary stores data in key–value pairs.
Declaration
Access Value
Output
📌 Use ! when you are sure the key exists.
Add / Update Value
Loop Through Dictionary
3️⃣ Set in Swift ⭐⭐
A Set stores unique, unordered values.
Declaration
Output
📌 Duplicate values are automatically removed.
Add & Remove
4️⃣ Mutable vs Immutable Collections ⭐⭐
Mutable (can change)
Immutable (cannot change)
5️⃣ Common Collection Operations ⭐⭐
Count
Check Empty
Contains
6️⃣ Collection Functions (Very Important) ⭐⭐⭐
map
Output-1:
filter
Output-2 :
reduce
Output-3:
7️⃣ Array vs Set vs Dictionary ⭐⭐⭐
| Feature | Array | Set | Dictionary |
|---|---|---|---|
| Order | Yes | No | No |
| Duplicate allowed | Yes | ❌ No | Keys ❌ |
| Access by index | Yes | ❌ | ❌ |
| Key–Value | ❌ | ❌ | ✅ |
8️⃣ When to Use What ❓
✔ Array → ordered data, indexing
✔ Set → unique values, fast lookup
✔ Dictionary → key–value mapping
9️⃣ Common Mistakes ❌
❌ Using wrong collection type
❌ Force-unwrapping dictionary values unsafely
❌ Expecting order in Set
❌ Modifying let collections
📌 Interview Questions (Swift Collections)
Q1. Difference between Array and Set?
👉 Array allows duplicates, Set does not
Q2. Is Dictionary ordered?
👉 No
Q3. Which collection is fastest for search?
👉 Set
Q4. What does map() do?
👉 Transforms elements
✅ Summary
✔ Swift has Array, Dictionary, Set
✔ Arrays are ordered
✔ Sets store unique values
✔ Dictionaries use key–value pairs
✔ map, filter, reduce are must-know
✔ Very important for Swift interviews
