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.

1...5

📌 Meaning: numbers 1 to 5


2️⃣ Types of Ranges in Swift ⭐

Swift mainly has 4 commonly used ranges:

  1. Closed Range (...)

  2. Half-Open Range (..<)

  3. One-Sided Ranges

  4. Range Types (Range, ClosedRange)


3️⃣ Closed Range (...) ⭐

Includes both start and end values.



 

Output

1 2 3 4 5

✔ Use when end value should be included


4️⃣ Half-Open Range (..<) ⭐

Includes start, excludes end.



 

Output

1 2 3 4

📌 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

let lastPart = numbers[2...]

From Start to Index

let firstPart = numbers[...2]

✔ 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, ..< → exclusive

  • Used in loops, arrays, switch, validation

  • One-sided ranges are powerful

  • Use contains() for clean conditions

  • Very important Swift interview topic

You may also like...