Swift Multidimensional Arrays
🍎 Swift Multidimensional Arrays – Complete Tutorial
A multidimensional array in Swift is an array of arrays.
They are commonly used for tables, matrices, grids, game boards, and UI layouts.
1️⃣ What is a Multidimensional Array?
An array that contains other arrays
Most common type: 2D Array
📌 Here, matrix is a 2D array (rows × columns).
2️⃣ Creating Multidimensional Arrays ⭐
2D Array (Int)
2D Array (String)
3️⃣ Accessing Elements ⭐
Syntax:
⚠️ Index out of range → runtime crash
4️⃣ Looping Through a 2D Array ⭐⭐
Nested for-in Loop (Most Common)
Loop with Row & Column Index
✔ Safe
✔ Interview-friendly
5️⃣ Modifying Multidimensional Arrays ⭐
Update Value
Append New Row
Append to Existing Row
6️⃣ Creating Empty 2D Array ⭐
7️⃣ Fixed Size Matrix Initialization ⭐⭐
📌 Very common interview question
8️⃣ Jagged Arrays (Uneven Rows) ⭐
Swift allows rows of different lengths.
✔ Flexible
❌ Be careful with indexing
9️⃣ Bounds Safety in Multidimensional Arrays ⭐
Always check indices.
✔ Prevents crashes
🔟 Multidimensional Arrays vs Dictionaries ⭐
| Feature | 2D Array | Dictionary |
|---|---|---|
| Ordered | ✔ Yes | ❌ No |
| Index-based | ✔ Yes | ❌ No |
| Grid-like data | ✔ Best | ❌ No |
| Named keys | ❌ No | ✔ Yes |
1️⃣1️⃣ Common Mistakes ❌
❌ Index out of range
❌ Assuming equal row sizes
❌ Using [Int][Int] (wrong syntax)
❌ Forgetting nested loops
📌 Interview Questions & MCQs
Q1. What is a 2D array in Swift?
A) Array of values
B) Dictionary
C) Array of arrays
D) Tuple
✅ Answer: C
Q2. Correct access syntax?
A) arr[row, col]
B) arr[row][col]
C) arr[row-col]
D) arr(row)(col)
✅ Answer: B
Q3. How to initialize 3×3 matrix with zeros?
A) Loop only
B) Array(repeating:)
C) Dictionary
D) Set
✅ Answer: B
Q4. Does Swift allow jagged arrays?
A) Yes
B) No
✅ Answer: A
Q5. What happens if index is out of range?
A) Returns nil
B) Compile error
C) Runtime crash
D) Ignored
✅ Answer: C
🔥 Real-Life Use Cases
✔ Game boards (chess, tic-tac-toe)
✔ Grid layouts
✔ Matrix calculations
✔ Seating charts
✔ Image pixel data
✅ Summary
Multidimensional arrays = arrays of arrays
Access using
[row][column]Use nested loops
Swift supports jagged arrays
Initialize fixed-size matrices with
Array(repeating:)Always handle bounds safely
Very important for Swift interviews & app logic
