Swift Ranges
🍎 Swift Ranges – Complete Tutorial
In Swift, ranges represent a sequence of values between two bounds.
They are widely used in loops, array slicing, conditions, validation, and pattern matching.
1️⃣ What is a Range in Swift?
A range defines values from a start to an end.
📌 Meaning: numbers 1 to 5
2️⃣ Types of Ranges in Swift ⭐
Swift mainly has 4 commonly used ranges:
Closed Range (
...)Half-Open Range (
..<)One-Sided Ranges
Range Types (
Range,ClosedRange)
3️⃣ Closed Range (...) ⭐
Includes both start and end values.
Output
✔ Use when end value should be included
4️⃣ Half-Open Range (..<) ⭐
Includes start, excludes end.
Output
📌 Very common with arrays
5️⃣ Ranges with Arrays ⭐⭐
Looping with Array Indices (Safe)
⚠️ Better practice:
Slicing Arrays Using Ranges
📌 Returns ArraySlice
6️⃣ One-Sided Ranges ⭐
From Index to End
From Start to Index
✔ Clean
✔ Interview-friendly
7️⃣ Checking Value in Range ⭐
Better (Swift way):
✔ Clean
✔ Readable
✔ Interview bonus
8️⃣ Ranges in switch Statement ⭐⭐
📌 Very common interview example
9️⃣ Range Types in Swift ⭐
| Type | Example |
|---|---|
Range | 1..<5 |
ClosedRange | 1...5 |
PartialRangeFrom | 2... |
PartialRangeUpTo | ..<5 |
PartialRangeThrough | ...5 |
🔟 Common Range Mistakes ❌
❌ Using ... instead of ..< in arrays
❌ Index out of range crash
❌ Forgetting slice returns ArraySlice
❌ Confusing endIndex with last index
🔍 Range vs Stride ⭐ (Interview)
Ranges increment by 1 only.
To skip values, use stride:
📌 Interview Questions & MCQs
Q1. Which range includes end value?
A) ..<
B) ...
✅ Answer: B
Q2. Best range for arrays?
A) ...
B) ..<
✅ Answer: B
Q3. What does 1..<5 produce?
A) 1 2 3 4 5
B) 1 2 3 4
C) 2 3 4 5
D) Error
✅ Answer: B
Q4. How to check value in range?
A) inRange()
B) contains()
C) check()
D) has()
✅ Answer: B
Q5. Can ranges be used in switch?
A) Yes
B) No
✅ Answer: A
🔥 Real-Life Use Cases
✔ Looping lists
✔ Pagination logic
✔ Validation (age, marks)
✔ Game levels
✔ UI indexing
✅ Summary
Ranges define a sequence of values
...→ inclusive,..<→ exclusiveUsed in loops, arrays, switch, validation
One-sided ranges are powerful
Use
contains()for clean conditionsVery important Swift interview topic
