Swift Arrays Indices & Bounds

🍎 Swift Arrays Indices & Bounds

Understanding Swift Arrays Indices & Bounds is critical in Swift because most array crashes happen due to index out of range errors.
This topic is very important for iOS development and interviews.


1️⃣ What are Array Indices in Swift?

  • Arrays use zero-based indexing

  • First element index → 0

  • Last element index → count - 1


 


2️⃣ Accessing Elements Using Indices ⭐


 

⚠️ Accessing an invalid index causes runtime crash:

// print(fruits[3]) ❌ Fatal error: Index out of range

3️⃣ Array Bounds (Lower & Upper) ⭐

Lower Bound

fruits.startIndex // 0

Upper Bound (⚠️ Not last index)

fruits.endIndex // 3

📌 Important Rule
Valid indices are:

startIndex <= index < endIndex

4️⃣ Correct Way to Access Last Element ⭐


 

OR (Best Practice):


 


5️⃣ Using indices Property (Safest Way ⭐⭐)


 

✔ Prevents index-out-of-range
✔ Interview favorite
✔ Recommended by Swift documentation


6️⃣ Checking Index Before Access ⭐


 

✔ Best practice for safe coding


7️⃣ Using first and last Safely ⭐


 

Safer with optional binding:


 


8️⃣ Looping with Bounds ❌ vs ✅

❌ Risky


 

✅ Safe


 


9️⃣ Array Slice Indices ⚠️ (Interview Trap)

Array slices keep original indices.


 

❌ This may crash:

// slice[0] ❌

✔ Correct:


 


🔟 Safe Subscript Extension (Advanced ⭐⭐)

Create a safe way to access array elements.


 

Usage:


 

✔ Prevents crashes
✔ Interview bonus


1️⃣1️⃣ Common Index & Bound Errors ❌

❌ Using endIndex as last index
❌ Assuming slice indices start at 0
❌ Ignoring optional results of first / last
❌ Accessing array without bounds check


🔍 Interview Comparison ⭐

Concept Meaning
startIndex First valid index
endIndex One past last index
Valid range startIndex..<endIndex
Safe loop array.indices

📌 Interview Questions & MCQs

Q1. First index of Swift array?

A) 1
B) 0
C) -1
D) Any

Answer: B


Q2. Is endIndex the last element?

A) Yes
B) No

Answer: B


Q3. Safest way to loop indices?

A) 0..<count
B) indices

Answer: B


Q4. What happens on index out of range?

A) Returns nil
B) Compile error
C) Runtime crash
D) Ignored

Answer: C


Q5. Type returned by array.first?

A) Element
B) Optional<Element>
C) Array
D) Index

Answer: B


🔥 Real-Life Use Cases

✔ TableView / CollectionView data source
✔ Pagination logic
✔ API response handling
✔ Crash prevention in apps
✔ Performance-safe coding


✅ Summary

  • Swift arrays are zero-indexed

  • Valid indices are startIndex..<endIndex

  • endIndex is not last index

  • Use indices, first, last for safety

  • Always guard against index out of bounds

  • Critical topic for Swift interviews & iOS apps

You may also like...