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

var names = [String]()

or

var names: [String] = []

3️⃣ Accessing Array Elements ⭐


 

⚠️ Accessing an invalid index causes runtime error.


4️⃣ Modifying Arrays (Mutable Arrays) ⭐

Add Elements

fruits.append("Orange")

Insert at Index

fruits.insert("Grapes", at: 1)

Update Element

fruits[0] = "Pineapple"

5️⃣ Removing Elements ⭐



6️⃣ Array Properties & Methods ⭐



7️⃣ Looping Through Arrays ⭐

For-in Loop


Using Index



8️⃣ Common Array Functions ⭐⭐

contains

fruits.contains("Apple")

sorted

let sortedFruits = fruits.sorted()

reversed

let reversedFruits = fruits.reversed()

9️⃣ Arrays with Different Initial Values ❌

Swift arrays must contain same data type.

❌ Invalid:

let mix = [1, "Apple"]

✔ Valid (using Any – not recommended):

let mix: [Any] = [1, "Apple"]

🔟 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 var for mutable, let for immutable

  • Zero-based indexing

  • Arrays are value types

  • Rich set of built-in methods

  • Core topic for Swift & iOS interviews

You may also like...