Swift Collections

Swift Tutorial

📦 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

var numbers = [1, 2, 3, 4]

Access Elements

print(numbers[0])

Output

1

Add Elements


Output

[1, 2, 3, 4, 5]

Loop Through Array



2️⃣ Dictionary in Swift ⭐⭐

A Dictionary stores data in key–value pairs.

Declaration

var marks = ["Math": 90, "Science": 85]

Access Value

print(marks["Math"]!)

Output

90

📌 Use ! when you are sure the key exists.


Add / Update Value

marks["English"] = 88

Loop Through Dictionary



3️⃣ Set in Swift ⭐⭐

A Set stores unique, unordered values.

Declaration


Output

{"Apple", "Banana"}

📌 Duplicate values are automatically removed.


Add & Remove



4️⃣ Mutable vs Immutable Collections ⭐⭐

Mutable (can change)

var arr = [1, 2, 3]
arr.append(4)

Immutable (cannot change)

let arr = [1, 2, 3]
// arr.append(4) ❌ error

5️⃣ Common Collection Operations ⭐⭐

Count

print(numbers.count)

Check Empty

print(numbers.isEmpty)

Contains

print(numbers.contains(3))

6️⃣ Collection Functions (Very Important) ⭐⭐⭐

map


Output-1:

[2, 4, 6, 8, 10]

filter


Output-2 :

[2, 4]

reduce


Output-3:

15

7️⃣ Array vs Set vs Dictionary ⭐⭐⭐

FeatureArraySetDictionary
OrderYesNoNo
Duplicate allowedYes❌ NoKeys ❌
Access by indexYes
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

You may also like...