Skip to main content
Swift for iOS Development
CHAPTER 08 Beginner

Swift Collections: Arrays, Dictionaries, and Sets

Updated: May 16, 2026
6 min read

# CHAPTER 8

Swift Collections: Arrays, Dictionaries, and Sets

1. Introduction

A variable holds a single piece of data. An object holds a single model. But what if you are building an Instagram clone? You don't have one photo; you have an infinite feed of photos. You need a data structure capable of holding massive lists of items. In Swift, these structures are called Collections. In this chapter, we will master the three core Swift Collections: Arrays (for ordered lists), Dictionaries (for fast key-value lookups), and Sets (for guaranteeing uniqueness).

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Create, modify, and iterate over Swift Arrays.
  • Understand zero-based indexing to extract array items.
  • Store and retrieve data using Key-Value pairs in Dictionaries.
  • Utilize Sets to perform ultra-fast math and ensure unique data.
  • Combine Collections with for-in loops to render data.

3. Arrays (Ordered Lists)

An Array is a list of items stored in a specific order. Because Swift is Type-Safe, an array can only hold ONE type of data (e.g., an array of Strings, or an array of Integers. You cannot mix them).
swift
123456789
// 1. Creating an Array of Strings
var highScores: [Int] = [100, 250, 80]
var shoppingList = ["Milk", "Eggs", "Bread"] // Type Inference!

// 2. Adding items
shoppingList.append("Apples")

// 3. Removing items
shoppingList.remove(at: 1) // Removes "Eggs"

Zero-Based Indexing: To grab an item out of an array, you ask for its position (Index). In computer science, we always start counting at Zero!

swift
12
print(shoppingList[0]) // Prints "Milk" (The 1st item)
// print(shoppingList[3]) // CRASH! Index out of range.

4. Dictionaries (Key-Value Pairs)

If you want to look up a user's phone number, an Array is terrible (you'd have to search millions of items one by one). A Dictionary is perfect. It stores data in Key-Value pairs. You provide the Key, and it instantly hands you the Value!
swift
1234567891011121314
// Syntax: [KeyType: ValueType]

// 1. Creating a Dictionary (Key is String, Value is Integer)
var phoneBook: [String: Int] = [
    "Alice": 5551234,
    "Bob": 5559876
]

// 2. Retrieving a value using the Key!
print(phoneBook["Alice"]) // Prints 5551234

// 3. Adding or Updating a value
phoneBook["Charlie"] = 5551111 // Adds new
phoneBook["Alice"] = 5559999   // Updates existing

5. Sets (Unordered & Unique)

A Set looks exactly like an Array, but it has two massive differences:
  1. 1. It has NO order (No indexing).
  1. 2. Every item MUST be unique. If you try to add "Apple" twice, it simply ignores the second one!

Sets are incredibly fast for searching.

swift
123456789
var visitedCountries: Set<String> = ["USA", "Japan", "France"]

// Inserting a duplicate does nothing!
visitedCountries.insert("Japan") 

// Lightning fast check!
if visitedCountries.contains("USA") {
    print("You have been to the US!")
}

6. Iterating through Collections

The true power of collections is automating them using the for-in loop we learned in Chapter 5.

Looping an Array:

swift
12345
let students = ["Alice", "Bob", "Charlie"]

for student in students {
    print("Welcome to class, \(student)!")
}

Looping a Dictionary: (It provides both the Key and Value!)

swift
12345
let grades = ["Math": "A", "Science": "B"]

for (subject, grade) in grades {
    print("You scored a \(grade) in \(subject).")
}

7. Higher-Order Functions (Advanced Magic)

Swift Collections have built-in superpowers like .filter and .map. These allow you to manipulate entire arrays in a single line of code without using heavy for loops!
swift
12345
let prices = [10, 20, 30, 40, 50]

// Give me a NEW array containing only items greater than 25!
let expensiveItems = prices.filter { $0 > 25 }
print(expensiveItems) // Prints [30, 40, 50]

8. Common Mistakes

  • Index Out of Range: The absolute most common crash in iOS development is Fatal Error: Index out of range. If an array has 3 items, its indexes are 0, 1, and 2. If your code asks for shoppingList[3], the app will instantly crash because that slot does not exist. Always check .count first!
  • Dictionary Nulls: When you ask a Dictionary for a value (phoneBook["Dave"]), what if Dave isn't in the book? Swift doesn't crash; it returns nil (nothing). We will learn how to handle nil in the next chapter!

9. Best Practices

  • Use Arrays for UI Lists: If you are building a feed (like Twitter or Instagram), always use an Array because the *order* of the posts matters.
  • Use Dictionaries for JSON: When you download data from the internet (JSON), it almost always comes formatted as Dictionaries (Key-Value pairs).

10. Exercises

  1. 1. Create an Array of Strings named colors containing "Red", "Green", and "Blue". Append "Yellow" to it.
  1. 2. Create a Dictionary named inventory where the Keys are Strings (item names) and the Values are Integers (quantity). Add an item.

11. Coding Challenges

Challenge: Create an array of Integers [5, 10, 15, 20]. Write a for-in loop that iterates over the array, multiplies each number by 2, and prints the result to the console.

12. MCQ Quiz with Answers

Question 1

In Swift, what is the defining characteristic of a Set compared to an Array?

Question 2

If you execute var list = ["A", "B", "C"] and then call print(list[1]), what will be printed to the console?

13. Interview Questions

  • Q: Contrast Arrays, Dictionaries, and Sets. Provide a specific, real-world iOS app scenario for when you would choose each specific collection type over the others.
  • Q: Explain the concept of "Zero-Based Indexing". Why does calling array[array.count] result in a fatal "Index out of bounds" crash?
  • Q: Briefly describe how higher-order functions like .filter and .map improve architectural readability over standard for loops.

14. FAQs

Q: Can I put Objects (like my custom Player struct) inside an Array? A: Absolutely! This is how all modern iOS apps work. You create a struct Post, and then your app holds a var feed: [Post] = []. You can fill it with 10,000 custom post objects!

15. Summary

In Chapter 8, we expanded our memory capacity from single variables to massive Collections. We established ordered data structures using Arrays, mastering zero-based indexing to extract data. We built lightning-fast lookup tables using Dictionaries, associating unique Keys with data Values. We ensured data uniqueness utilizing Sets, and leveraged our knowledge of Control Flow to iterate across these vast datasets seamlessly using for-in loops.

16. Next Chapter Recommendation

We hinted earlier that asking a Dictionary for a missing key returns nil. In older languages, nil destroys applications. Swift was built to survive it. Proceed to Chapter 9: Optionals and Error Handling.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·