Swift Array Slices

🍎 Swift Array Slices – Complete Tutorial

In Swift Array Slices lets you extract a portion of an array without copying all elements.
Slices are efficient, safe, and commonly used in iOS/macOS development and interviews.


1️⃣ What is an Array Slice in Swift?

An Array Slice:

  • Is a view into an existing array

  • Uses a range of indices

  • Does not copy data (memory efficient)

  • Type is ArraySlice<Element>, not Array<Element>



2️⃣ Creating an Array Slice ⭐

Using Closed Range (...)



Using Half-Open Range (..<)



3️⃣ Type of Array Slice ⭐ (Very Important)


📌 Interview trap: Slice is NOT an Array.


4️⃣ Looping Through an Array Slice ⭐


✔ Works just like an array


5️⃣ Accessing Slice Elements ⚠️

Array slices keep original indices.


❌ This may surprise beginners:

// slice[0] ❌ may crash

📌 Indices are inherited from original array.


6️⃣ Convert Array Slice to Array ⭐⭐

Often required in real projects.


✔ Resets indices to start from 0
✔ Interview favorite


7️⃣ Modifying Array Slices ❌

Array slices are read-only views.

❌ Not allowed:

// slice.append(6) ❌

✔ Convert to array first:

var arr = Array(slice)
arr.append(6)

8️⃣ Slicing Using prefix and suffix

Safer and cleaner approach.

prefix(_:)

let firstThree = numbers.prefix(3)

suffix(_:)

let lastTwo = numbers.suffix(2)

📌 These also return ArraySlice


9️⃣ Dropping Elements ⭐


✔ Useful for pipelines
✔ Returns ArraySlice


🔟 Array vs ArraySlice ⭐ (Interview)

FeatureArrayArraySlice
Type[Int]ArraySlice<Int>
MemoryOwn copyView (no copy)
IndicesStart at 0Original indices
Mutable✔ Yes❌ No

1️⃣1️⃣ Common Mistakes ❌

❌ Assuming slice is an array
❌ Accessing slice with index 0
❌ Modifying slice directly
❌ Forgetting to convert slice to array


📌 Interview Questions & MCQs

Q1. Type of array[1...3]?

A) Array
B) Slice
C) ArraySlice
D) List

Answer: C


Q2. Does ArraySlice copy data?

A) Yes
B) No

Answer: B


Q3. How to convert ArraySlice to Array?

A) slice.toArray()
B) Array(slice)
C) slice.array()
D) convert(slice)

Answer: B


Q4. Are ArraySlice indices reset?

A) Yes
B) No

Answer: B


Q5. Which is safer for slicing?

A) Index ranges
B) prefix / suffix

Answer: B


🔥 Real-Life Use Cases

✔ Pagination
✔ Processing subsets of data
✔ Performance-sensitive code
✔ Functional pipelines
✔ Interview coding questions


✅ Summary

  • ArraySlice is a view, not a copy

  • Created using ranges, prefix, suffix

  • Keeps original indices

  • Convert to Array when mutation is needed

  • More memory-efficient than arrays

  • Very important Swift interview topic

You may also like...