Swift Arrays
🍎 Swift Arrays – Complete Tutorial
In Swift, an Array is an ordered collection that stores multiple values of the same type.
Arrays are one of the most-used data structures in iOS, macOS, watchOS, and tvOS development.
1️⃣ What is an Array in Swift?
An array:
-
Stores values in ordered sequence
-
Uses zero-based indexing
-
Can be mutable (var) or immutable (let)
📌 Example:
2️⃣ Creating Arrays ⭐
Using Array Literal
Explicit Type Declaration
Empty Array
or
3️⃣ Accessing Array Elements ⭐
⚠️ Accessing an invalid index causes runtime error.
4️⃣ Modifying Arrays (Mutable Arrays) ⭐
Add Elements
Insert at Index
Update Element
5️⃣ Removing Elements ⭐
6️⃣ Array Properties & Methods ⭐
7️⃣ Looping Through Arrays ⭐
For-in Loop
Using Index
8️⃣ Common Array Functions ⭐⭐
contains
sorted
reversed
9️⃣ Arrays with Different Initial Values ❌
Swift arrays must contain same data type.
❌ Invalid:
✔ Valid (using Any – not recommended):
🔟 Value Type Behavior (Very Important ⭐)
Arrays in Swift are value types.
📌 a is not affected when b changes.
1️⃣1️⃣ Safe Access (Best Practice) ⭐
✔ Prevents crash
1️⃣2️⃣ Array vs Set (Interview ⭐)
| Feature | Array | Set |
|---|---|---|
| Order | ✔ Yes | ❌ No |
| Duplicate values | ✔ Allowed | ❌ Not allowed |
| Index-based | ✔ Yes | ❌ No |
| Performance | Medium | Faster search |
1️⃣3️⃣ Common Mistakes ❌
❌ Index out of range
❌ Using let when modification needed
❌ Mixing data types
❌ Ignoring value-type behavior
📌 Interview Questions & MCQs
Q1. Are Swift arrays zero-indexed?
A) Yes
B) No
✅ Answer: A
Q2. Which keyword creates mutable array?
A) let
B) var
✅ Answer: B
Q3. What happens if index is out of range?
A) Returns nil
B) Compile-time error
C) Runtime crash
D) Ignored
✅ Answer: C
Q4. Swift arrays are?
A) Reference types
B) Value types
✅ Answer: B
Q5. Which method adds element at end?
A) add()
B) push()
C) append()
D) insert()
✅ Answer: C
🔥 Real-Life Use Cases
✔ List of users
✔ TableView / CollectionView data
✔ API responses
✔ Shopping cart items
✔ App settings
✅ Summary
-
Arrays store ordered collection of same-type elements
-
Use
varfor mutable,letfor immutable -
Zero-based indexing
-
Arrays are value types
-
Rich set of built-in methods
-
Core topic for Swift & iOS interviews
